setID($invoiceId); } } public function setID($invoiceId) { $this->invoiceId = (int) $invoiceId; $loaded = $this->loadData(); return $loaded; } public function getID() { return $this->invoiceId; } public function getRequest($id) { $data = get_requests('', $id); if(is_array($data)) { return $data; } return 'fail'; } protected function loadData($force = true) { if (!$force && count($this->data)) { return false; } $invoiceModel = $this->getRequest($this->invoiceId); if($invoiceModel == 'fail') return false; $this->invoiceId = $invoiceModel['invoiceid']; if($this->invoiceId == 0) return false; $invoiceData["model"] = $invoiceModel; $invoiceData["invoiceid"] = $invoiceData["invoiceid"]; $invoiceData["balance"] = sprintf("%01.2f", $invoiceData["amount"]); $this->data = $invoiceData; return true; } public function getData($var = "") { $this->loadData(false); return isset($this->data[$var]) ? $this->data[$var] : $this->data; } protected function formatForOutput() { global $currency; $this->output = $this->data; $explode = explode(' ', $this->output["model"]["created_at"]); $this->output["datecreated"] = $explode[0]; //$currency = getCurrency($this->getData("userid")); //$array = array("subtotal", "credit", "tax", "total", "balance", "amountpaid"); foreach ($array as $v) { //$this->output[$v] = formatCurrency($this->output[$v]); } if (!function_exists("getClientsDetails")) { require ROOTDIR . "/includes/clientfunctions.php"; } foreach($this->data['model'] as $key => $val) { $clientsdetails[$key] = $val; } $array = array("invoicedate", "duedate", "datepaid"); foreach ($array as $v) { $this->output[$v] = substr($this->output["model"][$v], 0, 10) != "0000-00-00" ? fromMySQLDate($this->output[$v], $v == "datepaid" ? "1" : "0", 1) : ""; } $clientsdetails["country"] = $clientsdetails["countryname"]; $this->output["amount"] = $this->data['model']['amount']; $this->output["tax"] = $this->data['model']['tax']; $this->output["clientsdetails"] = $clientsdetails; $this->output["customfields"] = $customfields; //$taxData1 = getTaxRate(1, $clientsdetails["state"], $clientsdetails["countrycode"]); //$taxData2 = getTaxRate(2, $clientsdetails["state"], $clientsdetails["countrycode"]); $taxName1 = $taxData1["name"]; $taxName2 = $taxData2["name"]; if ($taxName1 != "") { $this->output["taxname"] = $taxName1; } else { $this->output["taxname"] = ""; $this->output["taxrate"] = "0"; } if ($taxName2 != "") { $this->output["taxname2"] = $taxName2; } else { $this->output["taxname2"] = ""; $this->output["taxrate2"] = "0"; } $this->output["pagetitle"] = 'Invoice #' . $this->output["model"]["invoiceid"]; $payto[] = $this->data['model']['seller_firstname'].' '.$this->data['model']['seller_firstname']; $payto[] = $this->data['model']['seller_address1']; if($this->data['model']['seller_address2']) $payto[] = $this->data['model']['seller_address2']; $payto[] = $this->data['model']['seller_city']; $payto[] = $this->data['model']['seller_state']; $payto[] = $this->data['model']['seller_postcode']; if(file_exists(ROOTDIR.'/uploads/user_uploads/'.$this->data['model']['relid'].'_profilephoto.jpg')) { $profilephoto = ROOTDIR.'/uploads/user_uploads/'.$this->data['model']['relid'].'_profilephoto.jpg'; }elseif(file_exists(ROOTDIR.'/uploads/user_uploads/'.$this->data['model']['relid'].'_profilephoto.png')) { $profilephoto = ROOTDIR.'/uploads/user_uploads/'.$this->data['model']['relid'].'_profilephoto.png'; }elseif(file_exists(ROOTDIR.'/uploads/user_uploads/'.$this->data['model']['relid'].'_profilephoto.jpeg')) { $profilephoto = ROOTDIR.'/uploads/user_uploads/'.$this->data['model']['relid'].'_profilephoto.jpeg'; }elseif(file_exists(ROOTDIR.'/uploads/user_uploads/'.$this->data['model']['relid'].'_profilephoto.gif')) { $profilephoto = ROOTDIR.'/uploads/user_uploads/'.$this->data['model']['relid'].'_profilephoto.gif'; }elseif(file_exists(ROOTDIR.'/uploads/user_uploads/'.$this->data['model']['relid'].'_profilephoto.JPG')) { $profilephoto = ROOTDIR.'/uploads/user_uploads/'.$this->data['model']['relid'].'_profilephoto.JPG'; } $this->output["profilephoto"] = $profilephoto; $this->output["payto"] = $payto; $this->output["seller_companyname"] = $this->data['model']['seller_companyname']; } public function getOutput($pdf = false) { $this->loadData(false); $this->formatForOutput(); if ($pdf) { $this->makePDFFriendly(); } return $this->output; } public function getLineItems($entityDecode = false) { $request = get_requests('', $this->getID()); $invoiceitems = array(); if(is_array($request['multirequest'])) { foreach($request['multirequest'] as $key => $data) { $qty = $data["qty"]; $description = $data["name"]; $amount = $data["price"]; $taxed = $data["taxed"] ? true : false; if ($entityDecode) { $description = htmlspecialchars(Sanitize::decode($description)); } else { $description = nl2br($description); } $invoiceitems[] = array("id" => (int) $key, "description" => $description, "rawamount" => $amount, "amount" => $amount, "taxed" => $taxed, "qty" => $qty); } } else { if ($entityDecode) { $description = htmlspecialchars(Sanitize::decode($request['description'])); } else { $description = nl2br($request['description']); } $invoiceitems[] = array("id" => (int) $request['id'], "description" => $description, "rawamount" => $request['amount'], "amount" => $request['amount'], "tax" => $request['istaxed']); } return $invoiceitems; } public function pdfCreate() { $this->pdf = new PDF(); return $this->pdf; } protected function makePDFFriendly() { $this->output["companyname"] = $this->output["seller_companyname"]; $this->output["companyaddress"] = $this->output["payto"]; $this->output = Sanitize::decode($this->output); return true; } public function pdfInvoicePage($invoiceId = 0) { $this->setID($invoiceId); $tplvars = $this->getOutput(true); if($tplvars['model']['id'] == '') return false; $tplvars["invoiceitems"] = $this->getLineItems(true); $tplvars["pdfFont"] = \Configuration::get_config("TCPDFFont"); $this->pdfAddPage("invoicepdf.tpl", $tplvars); return $tplvars['model']['invoiceid']; } public function pdfAddPage($tplfile, array $tplvars) { global $_LANG; $templateName = switch_theme(''.$_SESSION['user']['groupid']); $tplFileExtension = "." . pathinfo($tplfile, PATHINFO_EXTENSION); $baseTplFilename = preg_replace("/" . $tplFileExtension . "\$/", "", $tplfile); $headerTplFile = ROOTDIR . DIRECTORY_SEPARATOR . "templates" . DIRECTORY_SEPARATOR . $templateName . DIRECTORY_SEPARATOR . $baseTplFilename . "header" . $tplFileExtension; $footerTplFile = ROOTDIR . DIRECTORY_SEPARATOR . "templates" . DIRECTORY_SEPARATOR . $templateName . DIRECTORY_SEPARATOR . $baseTplFilename . "footer" . $tplFileExtension; if (file_exists($headerTplFile)) { $this->pdf->setHeaderTplFile($headerTplFile); } if (file_exists($footerTplFile)) { $this->pdf->setFooterTplFile($footerTplFile); } $this->pdf->setTemplateVars($tplvars); $this->pdf->setPrintHeader(true); $this->pdf->setPrintFooter(true); $this->pdf->AddPage(); $this->pdf->SetFont(\Configuration::get_config("TCPDFFont"), "", 10); $this->pdf->SetTextColor(0); foreach ($tplvars as $k => $v) { ${$k} = $v; } $pdf =& $this->pdf; include ROOTDIR . DIRECTORY_SEPARATOR . "templates" . DIRECTORY_SEPARATOR . $templateName . DIRECTORY_SEPARATOR . $tplfile; return true; } public function pdfOutput() { return $this->pdf->Output("", "S"); } public function getTotalBalance() { return $this->totalBalance; } public function getTotalBalanceFormatted() { return formatCurrency($this->getTotalBalance()); } } $value) { $key = db_make_safe_field($origkey); if (is_array($value)) { if ($key == "default") { $key = "`default`"; } if ($value['sqltype'] == "LIKE") { $criteria[] = "" . $key . " LIKE '%" . db_escape_string($value['value']) . "%'"; continue; } if ($value['sqltype'] == "NEQ") { $criteria[] = "" . $key . "!='" . db_escape_string($value['value']) . "'"; continue; } if ($value['sqltype'] == ">" && db_is_valid_amount($value['value'])) { $criteria[] = "" . $key . ">" . $value['value']; continue; } if ($value['sqltype'] == "<" && db_is_valid_amount($value['value'])) { $criteria[] = "" . $key . "<" . $value['value']; continue; } if ($value['sqltype'] == "<=" && db_is_valid_amount($value['value'])) { $criteria[] = "" . $origkey . "<=" . $value['value']; continue; } if ($value['sqltype'] == ">=" && db_is_valid_amount($value['value'])) { $criteria[] = "" . $origkey . ">=" . $value['value']; continue; } if ($value['sqltype'] == "TABLEJOIN") { $criteria[] = "" . $key . "=" . db_escape_string($value['value']) . ""; continue; } if ($value['sqltype'] == "IN") { $criteria[] = "" . $key . " IN (" . db_build_in_array($value['values']) . ")"; continue; } if ($value['sqltype'] == "DATEGREATER") { $criteria[] = "" . $origkey . ">=" . $value['value']; continue; } if ($value['sqltype'] == "DATELESS") { $criteria[] = "" . $origkey . "<=" . $value['value']; continue; } exit("Invalid input condition"); continue; } if (substr($key, 0, 3) == "MD5") { $key = explode("(", $origkey, 2); $key = explode(")", $key[1], 2); $key = db_make_safe_field($key[0]); $key = "MD5(" . $key . ")"; } else { $key = db_build_quoted_field($key); } $criteria[] = "" . $key . "='" . db_escape_string($value) . "'"; } $query .= " WHERE " . implode(" AND ", $criteria); } else { $query .= " WHERE " . $where; } } if ($orderby) { $orderbysql = tokenizeOrderby($orderby, $orderbyorder); $query .= " ORDER BY " . implode(",", $orderbysql); } if ($limit) { if (strpos($limit, ",")) { $limit = explode(",", $limit); $limit = (int)$limit[0] . "," . (int)$limit[1]; } else { $limit = (int)$limit; } $query .= " LIMIT " . $limit; } //echo $query.'
'; //return $query.'
'; $handle = (is_resource($userHandle) ? $userHandle : $connectmysql_mods); $result = mysqli_query($handle, $query); if (!$result && ($CONFIG['SQLErrorReporting'] || $mysql_errors)) { } ++$query_count; return $result; } endif; if (!function_exists('tokenizeOrderby')): function tokenizeOrderby($input, $default_ordering = "ASC", $userHandle = null) { $field_separator = ","; $field_begin = "`"; $field_end = "`"; $seg_qualifier = "."; $qualifier = $field_end . $seg_qualifier . $field_begin; $order_up_rev = "CSA "; $order_down_rev = "CSED "; if ($default_ordering) { $default_ordering = trim($default_ordering); } else { $default_ordering = "ASC"; } $default_ordering_rev = strrev(" " . $default_ordering); if ($default_ordering_rev != $order_up_rev && $default_ordering_rev != $order_down_rev) { $default_ordering_rev = $order_up_rev; } $tokenizedFields = array(); $i = 0; $field = strtok($input, $field_separator); while ($i < 30 && $field !== false) { $field = trim($field); if (!$field) { continue; } while (strpos($field, $field_begin) === 0) { $field = substr($field, 1); } $rev_field = strrev($field); $ordering_field_rev = ""; if (strpos($rev_field, $order_up_rev) === 0) { $ordering_field_rev .= $order_up_rev; $rev_field = substr($rev_field, strlen($order_up_rev)); } else { if (strpos($rev_field, $order_down_rev) === 0) { $ordering_field_rev .= $order_down_rev; $rev_field = substr($rev_field, strlen($order_down_rev)); } else { $ordering_field_rev .= $default_ordering_rev; } } while (strpos($rev_field, $field_end) === 0) { $rev_field = substr($rev_field, 1); } $field = strrev($rev_field); $field_parts = explode($qualifier, $field, 2); $safe_field_parts = array(); foreach ($field_parts as $key => $part) { $tmp_part = db_make_safe_field($part); if ($tmp_part === trim($part)) { $safe_field_parts[] = $tmp_part; continue; } } if (1 < count($safe_field_parts)) { $field = implode($qualifier, $safe_field_parts); } else { $field = array_shift($safe_field_parts); } if ($field) { $tokenizedFields[] = $field_begin . $field . $field_end . strrev($ordering_field_rev); } $field = strtok($field_separator); ++$i; } return $tokenizedFields; } endif; if (!function_exists('update_query')): function update_query($table, $array, $where, $userHandle = null) { global $query_count; global $mysql_errors; global $connectmysql_mods; $query = "UPDATE " . db_make_safe_field($table) . " SET "; foreach ($array as $key => $value) { $query .= db_build_quoted_field($key) . "="; $key = db_make_safe_field($key); if ($value === "now()") { $query .= "'" . date("Y-m-d H:i:s") . "',"; continue; } if ($value === "+1") { $query .= "`" . $key . "`+1,"; continue; } if ((is_array($value) && isset($value['type'])) && $value['type'] == "AES_ENCRYPT") { $query .= sprintf("AES_ENCRYPT('%s','%s'),", db_escape_string($value['text']) , db_escape_string($value['hashkey'])); continue; } if ($value === "NULL") { $query .= "NULL,"; continue; } if (substr($value, 0, 2) === "+=" && db_is_valid_amount(substr($value, 2))) { $query .= "`" . $key . "`+" . substr($value, 2) . ","; continue; } if (substr($value, 0, 2) === "-=" && db_is_valid_amount(substr($value, 2))) { $query .= "`" . $key . "`-" . substr($value, 2) . ","; continue; } $query .= "'" . db_escape_string($value) . "',"; } $query = substr($query, 0, 0 - 1); if (is_array($where)) { $query .= " WHERE"; foreach ($where as $key => $value) { if (substr($key, 0, 4) == "MD5(") { $key = "MD5(" . db_make_safe_field(substr($key, 4, 0 - 1)) . ")"; } else { $key = db_make_safe_field($key); if ($key == "order") { $key = "`order`"; } } $query .= " " . $key . "='" . db_escape_string($value) . "' AND"; } $query = substr($query, 0, 0 - 4); } else { if ($where) { $query .= " WHERE " . $where; } } //echo $query.'
'; $handle = (is_resource($userHandle) ? $userHandle : $connectmysql_mods); $result = mysqli_query($handle, $query); if (!$result && ($CONFIG['SQLErrorReporting'] || $mysql_errors)) { } ++$query_count; } endif; if (!function_exists('insert_query')): function insert_query($table, $array, $userHandle = null) { global $query_count; global $mysql_errors; global $connectmysql_mods; $fieldnamelist = $fieldvaluelist = ""; $query = "INSERT INTO " . db_make_safe_field($table) . " "; foreach ($array as $key => $value) { $fieldnamelist .= db_build_quoted_field($key) . ","; if ($value === "now()") { $fieldvaluelist .= "'" . date("Y-m-d H:i:s") . "',"; continue; } if ($value === "NULL") { $fieldvaluelist .= "NULL,"; continue; } $fieldvaluelist .= "'" . db_escape_string($value) . "',"; } $fieldnamelist = substr($fieldnamelist, 0, 0 - 1); $fieldvaluelist = substr($fieldvaluelist, 0, 0 - 1); $query .= "(" . $fieldnamelist . ") VALUES (" . $fieldvaluelist . ")"; //echo $query; $handle = (is_resource($userHandle) ? $userHandle : $connectmysql_mods); $result = mysqli_query($handle, $query); if (!$result && ($CONFIG['SQLErrorReporting'] || $mysql_errors)) { } ++$query_count; $id = mysqli_insert_id($connectmysql_mods); return $id; } endif; if (!function_exists('delete_query')): function delete_query($table, $where, $userHandle = null) { global $query_count; global $mysql_errors; global $connectmysql_mods; $query = "DELETE FROM " . db_make_safe_field($table) . " WHERE "; if (is_array($where)) { foreach ($where as $key => $value) { $query .= db_build_quoted_field($key) . "='" . db_escape_string($value) . "' AND "; } $query = substr($query, 0, 0 - 5); } else { $query .= $where; } $handle = (is_resource($userHandle) ? $userHandle : $connectmysql_mods); $result = mysqli_query($handle, $query); if (!$result && ($CONFIG['SQLErrorReporting'] || $mysql_errors)) { } ++$query_count; } endif; if (!function_exists('db_build_quoted_field')): function db_build_quoted_field($key) { $field_quote = "`"; $parts = explode(".", $key, 3); foreach ($parts as $k => $name) { $clean_name = db_make_safe_field($name); if ($clean_name !== $name) { exit("Unexpected input field parameter in database query."); } $parts[$k] = $field_quote . $clean_name . $field_quote; } return implode(".", $parts); } endif; if (!function_exists('full_query')): function full_query($query, $userHandle = null) { global $query_count; global $mysql_errors; global $connectmysql_mods; $handle = (is_resource($userHandle) ? $userHandle : $connectmysql_mods); $result = mysqli_query($handle, $query); if (!$result && ($CONFIG['SQLErrorReporting'] || $mysql_errors)) { } ++$query_count; return $result; } endif; if (!function_exists('get_query_val')): function get_query_val($table, $field, $where, $orderby = "", $orderbyorder = "", $limit = "", $innerjoin = "") { $result = select_query($table, $field, $where, $orderby, $orderbyorder, $limit, $innerjoin); $data = mysqli_fetch_array($result); return $data[0]; } endif; if (!function_exists('get_query_vals')): function get_query_vals($table, $field, $where, $orderby = "", $orderbyorder = "", $limit = "", $innerjoin = "") { $result = select_query($table, $field, $where, $orderby, $orderbyorder, $limit, $innerjoin); $data = mysqli_fetch_array($result); return $data; } endif; if (!function_exists('db_escape_string')): function db_escape_string($string) { global $connectmysql_mods; $string = mysqli_real_escape_string($connectmysql_mods, $string); return $string; } endif; if (!function_exists('db_escape_array')): function db_escape_array($array) { $array = array_map("db_escape_string", $array); return $array; } endif; if (!function_exists('db_escape_numarray')): function db_escape_numarray($array) { $array = array_map("intval", $array); return $array; } endif; if (!function_exists('db_build_in_array')): function db_build_in_array($array, $allow_empty = false) { $in = ""; foreach ($array as $k => $v) { if (!trim($v) && !$allow_empty) { unset($array[$k]); continue; } if (is_numeric($v)) { $v; continue; } $array[$k] = "'" . db_escape_string($v) . "'"; } return implode(",", $array); } endif; if (!function_exists('db_make_safe_field')): function db_make_safe_field($field) { return db_escape_string(preg_replace("/[^a-z0-9_.,]/i", "", $field)); } endif; if (!function_exists('db_build_update_array')): function db_build_update_array($fields, $arrayhandler = "serialize") { global $whmcs; $array = array(); foreach ($fields as $key) { $array[$key] = $whmcs->get_req_var($key); if (is_array($array[$key])) { if ($arrayhandler == "serialize") { $array[$key] = serialize($array[$key]); continue; } if ($arrayhandler == "implode") { $array[$key] = implode(",", $array[$key]); continue; } continue; } } return $array; } endif; if (!function_exists('db_make_safe_date')): function db_make_safe_date($date) { $dateparts = explode("-", $date); $date = (int)$dateparts[0] . "-" . str_pad((int)$dateparts[1], 2, "0", STR_PAD_LEFT) . "-" . str_pad((int)$dateparts[2], 2, "0", STR_PAD_LEFT); return db_escape_string($date); } endif; if (!function_exists('db_make_safe_human_date')): function db_make_safe_human_date($date) { $date = toMySQLDate($date); return db_make_safe_date($date); } endif; if (!function_exists('db_is_valid_amount')): function db_is_valid_amount($amount) { return preg_match('/^-?[0-9\.]+$/', $amount) === 1 ? true : false; } endif; if (!function_exists('mysqli_field_name')): function mysqli_field_name($result, $field_offset) { $properties = mysqli_fetch_field_direct($result, $field_offset); return is_object($properties) ? $properties->name : null; } endif; set_details_mods(); database_connect(); ?> 0) { while($res = mysqli_fetch_assoc($query)) { fire_pushnotification($res['push_id'], $title, $message, $img); } } } function fire_pushnotification($to, $title, $message, $img) { $msg = $message; $content = array( "en" => $msg ); $headings = array( "en" => $title ); if ($img == '') { $fields = array( 'app_id' => 'f990f727-92e2-4a93-aeaa-22b49825e8f5', "headings" => $headings, 'include_player_ids' => array($to), 'large_icon' => "", 'content_available' => true, 'contents' => $content ); } else { $ios_img = array( "id1" => $img ); $fields = array( 'app_id' => 'f990f727-92e2-4a93-aeaa-22b49825e8f5', "headings" => $headings, 'include_player_ids' => array($to), 'contents' => $content, "big_picture" => $img, 'large_icon' => "https://www.google.co.in/images/branding/googleg/1x/googleg_standard_color_128dp.png", 'content_available' => true, "ios_attachments" => $ios_img ); } $headers = array( 'Authorization: key=MDc0MWJlNTMtZmVkOS00ZWEzLTgyZGEtYWFlMjcxMzQwZDMy', 'Content-Type: application/json; charset=utf-8' ); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'https://onesignal.com/api/v1/notifications'); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields)); $result = curl_exec($ch); curl_close($ch); return $result; } ?>The '" . $messageName . "' email template has been disabled (" . Sanitize::makeSafeForOutput($template->subject) . ")

"; } return false; } if ($template['group'] == "invoice") { $appointment_query = select_query("tblclient_requests", "*", array("customer_relid"=>$userid,"relid"=>$extra['uid'], "id"=>$extra['id'])); $appointment_data = mysqli_fetch_array($appointment_query); $clientid = $appointment_data['relid']; $clientdetails = getuserdetails($clientid); $email_merge_fields['fullname'] = $clientdetails['firstname'].' '.$clientdetails['lastname']; $email_merge_fields['fname'] = $clientdetails['firstname']; $email_merge_fields['email'] = $clientdetails['email']; $email_merge_fields['paycode'] = $appointment_data['paycode']; $email_merge_fields['description'] = $appointment_data['description']; $email_merge_fields['date'] = date("d/m/Y", strtotime($appointment_data['datetime'])); $email_merge_fields['time'] = date("H:i", strtotime($appointment_data['datetime'])).' - '. date("H:i", strtotime($appointment_data['endtime'])); $email_merge_fields['amount'] = '£'.$appointment_data['amount']; $header_title = "Invoice #".$appointment_data['invoiceid']; $fromemail = "paymentrequests@pay-me.co.uk"; } else { if($template['group'] == 'appointment') { $appointment_query = select_query("tblclients_appointments", "*", array("customer_relid"=>$userid,"relid"=>$extra['uid'], "id"=>$extra['id'])); $appointment_data = mysqli_fetch_array($appointment_query); $clientid = $appointment_data['relid']; $clientdetails = getuserdetails($clientid); $email_merge_fields['fullname'] = $clientdetails['firstname'].' '.$clientdetails['lastname']; $email_merge_fields['fname'] = $clientdetails['firstname']; $email_merge_fields['email'] = $clientdetails['email']; $email_merge_fields['description'] = $appointment_data['description']; $email_merge_fields['date'] = date("d/m/Y", strtotime($appointment_data['datetime'])); $email_merge_fields['time'] = date("H:i", strtotime($appointment_data['datetime'])).' - '. date("H:i", strtotime($appointment_data['endtime'])); $header_title = "Appointment Confirmed"; $fromemail = "appointments@pay-me.co.uk"; } else { if($template['group'] == 'request') { $header_title = "New Payment Request"; $appointment_query = select_query("tblclient_requests", "*", array("customer_relid"=>$userid,"relid"=>$extra['uid'], "id"=>$extra['id'])); $appointment_data = mysqli_fetch_array($appointment_query); $clientid = $appointment_data['relid']; $clientdetails = getuserdetails($clientid); $email_merge_fields['fullname'] = $clientdetails['firstname'].' '.$clientdetails['lastname']; $email_merge_fields['fname'] = $clientdetails['firstname']; $email_merge_fields['email'] = $clientdetails['email']; $email_merge_fields['paycode'] = $appointment_data['paycode']; $email_merge_fields['description'] = $appointment_data['description']; $email_merge_fields['date'] = date("d/m/Y", strtotime($appointment_data['datetime'])); $email_merge_fields['time'] = date("H:i", strtotime($appointment_data['datetime'])).' - '. date("H:i", strtotime($appointment_data['endtime'])); $header_title = "Payment Request: £".$appointment_data['amount']; $fromemail = "paymentrequests@pay-me.co.uk"; } } } if ($userid) { $result2 = select_query("tblclients_customers", "*", array("id" => $userid)); $data2 = mysqli_fetch_array($result2); if (empty($firstname) && empty($email)) { $firstname = $data2["firstname"]; $email = $data2["email"]; } $lastname = $data2["lastname"]; $companyname = $data2["companyname"]; $address1 = $data2["address1"]; $address2 = $data2["address2"]; $city = $data2["city"]; $state = $data2["state"]; $postcode = $data2["postcode"]; $country = $data2["country"]; $phonenumber = $data2["phonenumber"]; $datecreated = fromMySQLDate($data2["created_at"], 0, 1); //$currency = getCurrency($userid); $totalInvoices = get_query_val("tblclient_requests", "SUM(amount)", array("customer_relid" => $userid, "status" => "Unpaid")); } if (!$email) { return false; } $fname = trim($firstname . " " . $lastname); if ($companyname) { $fname .= " (" . $companyname . ")"; } $email_merge_fields["client_id"] = $userid; $email_merge_fields["client_name"] = $fname; $email_merge_fields["client_first_name"] = $firstname; $email_merge_fields["client_last_name"] = $lastname; $email_merge_fields["client_company_name"] = $companyname; $email_merge_fields["client_email"] = $email; $email_merge_fields["client_address1"] = $address1; $email_merge_fields["client_address2"] = $address2; $email_merge_fields["client_city"] = $city; $email_merge_fields["client_state"] = $state; $email_merge_fields["client_postcode"] = $postcode; $email_merge_fields["client_country"] = $country; $email_merge_fields["client_phonenumber"] = $phonenumber; $email_merge_fields["client_signup_date"] = $datecreated; foreach($email_merge_fields as $key => $val) { $before[] = "{".$key."}"; $after[] = $val; } $subject = str_replace($before, $after, $subject); $message = str_replace($before, $after, $message); $pretext = '
'.$header_title.'
'.$message.'
'; if ($attachment) { $attachment = explode("|", $attachment); $attachments = array(); foreach ($attachment as $file) { $attachments[$attachments_dir . '/' . $file] = $file; } } if (!trim($subject) && !trim($message)) { logActivity("EMAILERROR: Email Message Empty so Aborting Sending - Template Name " . $messageName . " ID " . $func_id); return false; } try { $get_credits = getEmailCredits('', $extra['uid']); $total_credits = number_format(($get_credits['balance'] + $get_credits['paidbalance']), 0); if($currentPackage['payment_reminders'] == 'Unlimited'){ $total_credits = 1; } if($total_credits == 0) { logActivity("No Email Credits", $extra['uid'], $v['customerid']); return 'nocredits'; } else { $mail = new Mail("Pay-Me", $fromemail); $mail->AddAddress($email, $firstname . " " . $lastname); $mail->Subject = $subject; $message = $mail->setMessage($pretext, nl2br($pretext)); $mail->AddReplyTo($email_merge_fields['email'], $email_merge_fields['fullname']); if (is_array($attachments)) { foreach ($attachments as $filename => $displayname) { $mail->AddAttachment($filename, $displayname); } } /*$smtp_debug = (int) $whmcsAppConfig["smtp_debug"]; if (0 < $smtp_debug) { $mail->SMTPDebug = $smtp_debug; if (!WHMCS\Environment\Php::isCli()) { $mail->Debugoutput = "html"; } }*/ if ($email_debug) { echo "Email: " . Sanitize::makeSafeForOutput($email) . "
Subject: " . Sanitize::makeSafeForOutput($subject) . "
Message: " . Sanitize::makeSafeForOutput($message) . "
Attachment: " . Sanitize::makeSafeForOutput($attachmentfilename) . "

"; return false; } if ($email_preview) { echo $message; return false; } $mail->send(); if ($displayresult) { echo "

Email Sent Successfully to " . Sanitize::makeSafeForOutput((string) $firstname . " " . $lastname) . "

"; } insert_query("tblclients_emails", array("relid" => $extra['uid'], "customer_relid"=>$userid, "subject" => $subject, "message" => $message, "date" => "now()", "to" => $email, "created_at"=>"now()")); $emailuserlink = 0 < $userid ? " - Customer ID: " . $userid : ""; logActivity("Email Sent to " . $firstname . " " . $lastname . " (" . $subject . ") " . $emailuserlink, $extra['uid'], $userid); $mail->ClearAddresses(); if($currentPackage['payment_reminders'] != 'Unlimited'){ deduct_Email(array("userid"=>$extra['uid'])); } return 'sent'; } } catch (phpmailerException $e) { logActivity("Email Sending Failed - " . $e->getMessage() . " (Customer ID: " . $userid . " - Subject: " . $subject . ")", "none"); if ($displayresult) { echo "

Email Sending Failed - " . $e->errorMessage() . "

"; } } catch (Exception $e) { logActivity("Email Sending Failed - " . $e->getMessage() . " (Customer ID: " . $userid . " - Subject: " . $subject . ")", "none"); if ($displayresult) { echo "

Email Sending Failed - " . $e->getMessage() . "

"; } } return true; }pdfCreate(); $check = $invoice->pdfInvoicePage($requestid); if($checkPDF) { if(!$check) return false; return true; } if(!$check) return false; $pdfdata = $invoice->pdfOutput(); return array("data"=>$pdfdata, "id"=>$check); } function GenerateInvoice($id, $send = FALSE) { $viewpdf = false; if($_GET['type'] == 'i') $viewpdf = true; $pdfdata = pdfInvoice($id); if(!$pdfdata) return false; $filenameSuffix = preg_replace("|[\\\\/]+|", "-", $id); if($send) { $date = date('ymdhis'); $link = '/var/www/vhosts/paymyservices.co.uk/public_html/application/uploads/invoices/Invoice_'.$pdfdata['id'].'_'.$date.'.pdf'; unlink($link); file_put_contents( $link, $pdfdata['data']); return 'Invoice_'.$pdfdata['id'].'_'.$date.'.pdf'; } header("Pragma: public"); header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0, private"); header("Cache-Control: private", false); header("Content-Type: application/pdf"); header("Content-Disposition: " . ($viewpdf ? "inline" : "attachment") . "; filename=\"" . 'Invoice' . '_'.$pdfdata['id'] .".pdf\""); header("Content-Transfer-Encoding: binary"); header("Content-Length: " . strlen($pdfdata['data'])); echo $pdfdata['data']; die(); }decode($val); return $input->encode($val); } public static function convertToCompatHtml($val) { $input = new Sanitize(); $val = $input->decode($val); $val = $input->decode($val); return $input->encodeToCompatHTML($val); } public static function encode($val) { $input = new Sanitize(); if (is_bool($val)) { return $val; } if (is_numeric($val)) { return $val; } if (is_string($val)) { return $input->encodeString($val); } if (is_array($val)) { return $input->encodeArray($val); } if (is_object($val)) { return $val; } return ""; } public static function encodeToCompatHTML($val) { $input = new Sanitize(); if (is_bool($val)) { return $val; } if (is_numeric($val)) { return $val; } if (is_string($val)) { return $input->encodeStringToCompatHTML($val); } if (is_array($val)) { return $input->encodeArrayToCompatHTML($val); } if (is_object($val)) { return $val; } return ""; } public static function decode($val) { $input = new Sanitize(); if (is_bool($val)) { return $val; } if (is_numeric($val)) { return $val; } if (is_string($val)) { return $input->decodeString($val); } if (is_array($val)) { return $input->decodeArray($val); } if (is_object($val)) { return $val; } return ""; } protected function encodeArray($array) { foreach ($array as $k => $v) { $array[$k] = $this->encode($v); } return $array; } protected function encodeArrayToCompatHTML($array) { foreach ($array as $k => $v) { $array[$k] = $this->encodeToCompatHTML($v); } return $array; } protected function decodeArray($array) { foreach ($array as $k => $v) { $array[$k] = $this->decode($v); } return $array; } protected function encodeString($val) { return htmlspecialchars($val, ENT_QUOTES); } protected function encodeStringToCompatHTML($val) { static $mask = NULL; if (!isset($mask)) { $mask = $this->getCompatBitmask(); } return htmlspecialchars($val, $mask); } public function getCompatBitmask() { $mask = ENT_COMPAT; if (defined("ENT_HTML401")) { $mask = $mask | ENT_HTML401; } return $mask; } protected function decodeString($val) { $val = str_replace(" ", " ", $val); return html_entity_decode($val, ENT_QUOTES); } public static function maskEmailVerificationId($message) { $mask = "verificationId=%2A"; $regex = "%verificationId=[0-9a-f]{40}%i"; $maskedMessage = preg_replace($regex, $mask, $message); return $maskedMessage; } public static function escapeSingleQuotedString($content) { $content = str_replace("\\", "\\\\", $content); $content = str_replace("'", "\\'", $content); return $content; } public static function stripTags($val, $allowedTags = "") { $input = new Sanitize(); if (is_bool($val)) { return $val; } if (is_numeric($val)) { return $val; } if (is_string($val)) { return $input->stripTagsFromString($val, $allowedTags); } if (is_array($val)) { return $input->stripTagsFromArray($val, $allowedTags); } if (is_object($val)) { return $val; } return ""; } protected function stripTagsFromString($val, $allowedTags) { $val = $this->decodeString($val); $val = strip_tags($val, $allowedTags); return $this->encodeString($val); } protected function stripTagsFromArray(array $array, $allowedTags) { foreach ($array as $k => $v) { $array[$k] = $this->stripTags($v, $allowedTags); } return $array; } }$_SESSION['uid'], "group"=>$v['group'], "type"=>"email", "name"=>$v['name'], "subject"=>$v['subject'], "message"=>$v['message'], "fromname"=>"{fullname}", "fromemail"=>"{email}","custom"=>"1","plaintext"=>"1","created_at"=>"now()"); $insertid = insert_query("tblclient_emailtemplates", $insert); echo $insertid; } else { update_query("tblclient_emailtemplates", array("subject"=>$v['subject'], "message"=>$v['message']), array("id"=>$v['id'], "relid"=>$_SESSION['uid'], "custom"=>"1")); echo $v['id']; } die(); } function get_template_content($userid, $type = NULL, $name) { if($type) { $find = select_query("tblclient_emailtemplates", "*", array("relid"=>$userid,"type"=>$type,"name"=>$name,"custom"=>"1")); } else { $find = select_query("tblclient_emailtemplates", "*", array("relid"=>$userid,"name"=>$name,"custom"=>"1")); } if(mysqli_num_rows($find) > 0) { $data = mysqli_fetch_array($find); } else { if($type) { $find = select_query("tblclient_emailtemplates", "*", array("relid"=>"0","type"=>$type,"name"=>$name,"custom"=>"0")); } else { $find = select_query("tblclient_emailtemplates", "*", array("relid"=>"0","name"=>$name,"custom"=>"0")); } $data = mysqli_fetch_array($find); } return $data; } function get_email_templates($type, $id = NULL) { $uid = $_SESSION['uid']; if($id) { $query = full_query("SELECT * FROM `tblclient_emailtemplates` WHERE `id` = '$id'"); $res = mysqli_fetch_array($query); $name = $res['name']; $query2 = full_query("SELECT * FROM `tblclient_emailtemplates` WHERE `relid` = '$uid' AND `name` LIKE '$name' "); if(mysqli_num_rows($query2) > 0) { $data = mysqli_fetch_array($query2); return $data; } return $res; } else { $query = full_query("SELECT * FROM `tblclient_emailtemplates` WHERE `relid` = '0' AND `type` LIKE '$type' "); while($res = mysqli_fetch_assoc($query)) { $arr[$res['name']] = $res; } $query = full_query("SELECT * FROM `tblclient_emailtemplates` WHERE `relid` = '$uid' AND `type` LIKE '$type' "); while($res = mysqli_fetch_assoc($query)) { $arr[$res['name']] = $res; } return $arr; } }
We have received your request to reset your password.

Your New Password is:
'.$password2.'

Thanks,
Admin'; $postfields["customsubject"] = 'Your New Password'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_TIMEOUT, 100); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields); $data2 = curl_exec($ch); curl_close($ch); } } } function checkLogin($email, $type = NULL, $isadmin = NULL) { if($isadmin) { $results['userid'] = $email; return $results; } $query = full_query("SELECT * FROM tblclients WHERE email='".$email."'"); if(mysqli_num_rows($query) > 0) { $data = mysqli_fetch_array($query); $results['userid'] = $data['id']; } else { $results = 'nouser'; } return $results; } function invoiceLogin_NSB($v) { global $install_path; if($install_path) { $rooturl = '//' . $_SERVER['HTTP_HOST'] . '/' . $install_path; } else { $rooturl = '//' . $_SERVER['HTTP_HOST'] . '/' ; } destroy_multi(); destroy_login(); $userid = $_GET['p2']; $invoiceid = $_GET['p3']; $_SESSION['nsb'] = true; $_SESSION['uid'] = $userid; $_SESSION['upw'] = sha1($userid . $newpasshash . $_SERVER['REMOTE_ADDR'] . substr(sha1($cc_encryption_hash),0,20)); header('Location: '.$rooturl.'invoices/'.$userid.'/'.$invoiceid.'/aCh5GefD/'); } function destroy_multi() { $_SESSION['in_account'] = false; $_SESSION['refer'] = ''; $_SESSION['customlogo'] = ''; $_SESSION['logowidth'] = ''; $_SESSION['primary'] = ''; $_SESSION['secondary'] = ''; $_SESSION['WorkbookSetting'] = ''; $_SESSION['content'] = ''; $_SESSION['siteid'] = ''; $_SESSION['invoicelogin'] = ''; } function destroy_login() { global $install_path; if($install_path) { $rooturl = '//' . $_SERVER['HTTP_HOST'] . '/' . $install_path; } else { $rooturl = '//' . $_SERVER['HTTP_HOST'] . '/' ; } $_SESSION['uid'] = ''; $_SESSION['aid'] = ''; $_SESSION['accounts'] = ''; $_SESSION['in_account'] = false; $_SESSION['multiaccount'] = false; $_SESSION['user'] = ''; $_SESSION['nsb'] = false; $_SESSION['refer'] = ''; $_SESSION['customlogo'] = ''; $_SESSION['logowidth'] = ''; $_SESSION['primary'] = ''; $_SESSION['secondary'] = ''; $_SESSION['WorkbookSetting'] = ''; $_SESSION['content'] = ''; $_SESSION['siteid'] = ''; $_SESSION['invoicelogin'] = ''; //header('Location: '.$rooturl); } function displayMultiAccounts() { return $arr; } function adminLogin($v) { destroy_multi(); destroy_login(); if($v['auth'] == 'zcDOyyJN05QI') { $var = checkLogin($v['email'], '', true); if($var != 'nouser') { $userid = $var['userid']; $_SESSION['aid'] = 1; $_SESSION['uid'] = $userid; $_SESSION['upw'] = sha1($userid . $newpasshash . $_SERVER['REMOTE_ADDR'] . substr(sha1($cc_encryption_hash),0,20)); } } header('Location: /'); } function check_device_id($id) { if($id) { $_SESSION['device_id'] = $id; $check = app_query("SELECT * FROM app_login WHERE device_id = '$id'"); if(mysqli_num_rows($check) > 0) { $data = mysqli_fetch_array($check); $var = checkLogin($data['email'], 'bt'); $var2 = checkLogin($data['email'], 'be'); if($var != 'nouser') { } if($var != 'nouser') { $userid = $var['userid']; $_SESSION['aid'] = 1; $_SESSION['uid'] = $userid; $_SESSION['upw'] = sha1($userid . $newpasshash . $_SERVER['REMOTE_ADDR'] . substr(sha1($cc_encryption_hash),0,20)); } else { } header('Location: /'); } } } function login($v) { destroy_login(); $return = processLogin($v); if($return == 'notloggedin') { $_SESSION['uid'] = ''; $_SESSION['error_login'] = 'WrongUser'; } else { $_SESSION['error_login'] = ''; $_SESSION['uid'] = $return; header('location: /'); } } function processLogin($v) { $var = apiUserid($v['email'], $v['password']); // Check BT $_SESSION['error_login'] = ''; if($var != 'nouser') { $userid = $var['userid']; $passwordhash = $var['passwordhash']; send_pushnotification($userid, "New Log-in Notification", "A new device has just accessed your account. If that was not you please change your password and force logout through the app.", ""); insert_query("tblclients_ios", array("relid"=>$userid, "uuid"=>$v['uuid'], "push_id"=>$v['pushid'])); full_query("INSERT INTO `tblclients_notifications` (`id`, `relid`, `noti_type`, `header`, `message`, `datetime`, `viewed`, `push_ios`, `push_sent`) VALUES (NULL, '".$userid."', 'danger', 'New Log-in Notification', 'A new device has just accessed your account. If that was not you please change your password and force logout through the app.', now(), '0', '1', now()); "); $newpasshash = getWHMCSDetails($userid, 'password'); $cc_encryption_hash = $CONFIG['whmcs_hash']; if(!session_id()) session_start(); $ip = $_SERVER['REMOTE_ADDR']; $_SESSION['uid'] = $userid; $_SESSION['upw'] = sha1($userid . $newpasshash . $_SERVER['REMOTE_ADDR'] . substr(sha1($cc_encryption_hash),0,20)); return $userid; } else { return 'notloggedin'; } } if (!function_exists('apiUserid')) { function apiUserid($email, $pass) { global $CONFIG; $url = $CONFIG['whmcs_url']; # URL to WHMCS API file $username = $CONFIG['whmcs_user']; # Admin username goes here $password = $CONFIG['whmcs_pass']; # Admin password goes here $postfields["username"] = $username; $postfields["password"] = md5($password); $postfields["action"] = "validatelogin"; $postfields["email"] = $email; $postfields["password2"] = $pass; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_TIMEOUT, 100); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields); $data = curl_exec($ch); curl_close($ch); $data = explode(";",$data); foreach ($data AS $temp) { $temp = explode("=",$temp); $results[$temp[0]] = $temp[1]; } //print_r($results); if ($results["result"]=="success") { $query = full_query('SELECT * FROM tblclients WHERE id="'.$results['userid'].'"'); $data2 = mysqli_fetch_array($query); //print_r($data2); if($data2['status'] == 'Closed'): return 'nouser'; else: return $results; endif; } else { return 'nouser'; } } } if (!function_exists('getWHMCSDetails')): function getWHMCSDetails($userid, $var) { $query = full_query('SELECT * FROM tblclients WHERE id="'.$userid.'"'); $res = mysqli_fetch_array($query); return $res[$var]; } endif; if (!function_exists('encryptPassword')): function encryptPassword($pass) { $url = $CONFIG['whmcs_url']; # URL to WHMCS API file $username = $CONFIG['whmcs_user']; # Admin username goes here $password = $CONFIG['whmcs_pass']; # Admin password goes here $postfields["username"] = $username; $postfields["password"] = md5($password); $postfields["action"] = "encryptpassword"; $postfields["password2"] = $pass; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_TIMEOUT, 100); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields); $data = curl_exec($ch); curl_close($ch); //echo 'Email: '.$email; $data = explode(";",$data); foreach ($data AS $temp) { $temp = explode("=",$temp); $results[$temp[0]] = $temp[1]; } if ($results["result"]=="success") { return $results['password']; } } endif; if (!function_exists('apiUserid')): function apiUserid($email, $pass) { $url = $CONFIG['whmcs_url']; # URL to WHMCS API file $username = $CONFIG['whmcs_user']; # Admin username goes here $password = $CONFIG['whmcs_pass']; # Admin password goes here $postfields["username"] = $username; $postfields["password"] = md5($password); $postfields["action"] = "validatelogin"; $postfields["email"] = $email; $postfields["password2"] = $pass; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_TIMEOUT, 100); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields); $data = curl_exec($ch); curl_close($ch); $data = explode(";",$data); foreach ($data AS $temp) { $temp = explode("=",$temp); $results[$temp[0]] = $temp[1]; } /*echo '
';
print_r($results);
echo '
';*/ if ($results["result"]=="success") { $query = full_query('SELECT * FROM tblclients WHERE id="'.$results['userid'].'"'); $data2 = mysqli_fetch_array($query); if($data2['status'] == 'Closed'): return 'nouser'; else: return $results; endif; } else { return 'nouser'; } } endif; ?>paperSize = $paperSize; parent::__construct("P", "mm", strtoupper($paperSize), $unicode, \Configuration::get_config("Charset"), false); $this->SetCreator("Pay-Me"); $this->SetAuthor("Pay-Me"); $this->SetMargins(15, 25, 15); $this->SetFooterMargin(15); $this->SetAutoPageBreak(true, 25); $this->setLanguageArray(array("a_meta_charset" => \Configuration::get_config("Charset"), "a_meta_dir" => "ltr", "a_meta_language" => "en", "w_page" => "page")); } public function setHeaderTplFile($headerTplFile) { $this->headerTplFile = $headerTplFile; } public function setFooterTplFile($footerTplFile) { $this->footerTplFile = $footerTplFile; } public function setTemplateVars(array $tplVars) { $this->templateVars = $tplVars; } public function Header() { if ($this->headerTplFile) { foreach ($this->templateVars as $k => $v) { ${$k} = $v; } $pdf =& $this; include $this->headerTplFile; } } public function Footer() { if ($this->footerTplFile) { foreach ($this->templateVars as $k => $v) { ${$k} = $v; } $pdf =& $this; include $this->footerTplFile; } } public function SetFont($family, $style = "", $size = NULL, $fontfile = "", $subset = "default", $out = true) { $adminFontSetting = \Configuration::get_config("TCPDFFont"); if (in_array($adminFontSetting, $this->fontlist)) { $familyOverride = $adminFontSetting; } else { if (in_array($family, $this->fontlist)) { $familyOverride = $family; } else { $familyOverride = PDF_FONT_NAME_MAIN; } } parent::SetFont($familyOverride, $style, $size, $fontfile, $subset, $out); } } $orderid, 'sendemail' => true, ); $adminUsername = ''; // Optional for WHMCS 7.2 and later $results = localAPI($command, $postData, $adminUsername); } function buyPlan($v) { $pid = $v['pid']; if($pid == '4') { $v['bundle'] = '20'; $v['emailbundle'] = '50'; }elseif($pid == '3') { $v['bundle'] = '100'; $v['emailbundle'] = '500'; }elseif($pid == '2') { $v['bundle'] = '200'; $v['emailbundle'] = '10000'; } $order = api_AddOrder($pid); $invoiceid = $order['invoiceid']; $orderid = $order['orderid']; if($invoiceid > 0) { $capture = api_CapturePayment($invoiceid); if($capture['result'] == 'success') { acceptOrder($orderid); return array("result"=>'success', "invoiceid"=>$invoiceid, "orderid"=>$orderid, "bundle"=>$v['bundle'], "emailbundle"=>$v['emailbundle']); } else { return array("result"=>'error', "invoiceid"=>$invoiceid, "orderid"=>$orderid, "bundle"=>$v['bundle'], "emailbundle"=>$v['emailbundle']); } } else { acceptOrder($orderid); return array("result"=>'success', "invoiceid"=>$invoiceid, "orderid"=>$orderid, "bundle"=>$v['bundle'], "emailbundle"=>$v['emailbundle']); } }= 0) { $arr['day'] = $v['day']; if($v['payment_time']) $arr['time'] = $v['payment_time']; if($v['send_sms'] == 'true'){ $arr['send_sms'] = 1; } else { $arr['send_sms'] = 0; } update_query("tblclient_notification_settings", $arr, $where); print_r($arr); } } if($v['appointreminders']) { if($v['appointreminders'] =='no'){ $appoint = '0'; } else { $appoint="1"; } $arr['appointment_reminders'] = $appoint; //$query = full_query('UPDATE tblclient_notification_settings SET payment_reminders="'.$remind.'" WHERE relid="'.$_SESSION['uid'].'"'); update_query("tblclient_notification_settings", $arr, $where); if($v['day'] >= 0) { $arr['appointment_day'] = $v['day']; if($v['time']) $arr['appointment_time'] = $v['time']; if($v['send_sms'] == 'true'){ $arr['appointment_send_sms'] = 1; } else { $arr['appointment_send_sms'] = 0; } update_query("tblclient_notification_settings", $arr, $where); } } if($v['hasinvoicing']) { if($v['hasinvoicing'] =='no'){ $hasinvoicing = '0'; } else { $hasinvoicing="1"; } $arr['hasinvoicing'] = $hasinvoicing; $arr['invoiceaddress'] = $v['invoiceaddress']; update_query("tblclient_notification_settings", $arr, $where); } } function get_notification_settings() { $notification_settings = full_query("SELECT * FROM tblclient_notification_settings WHERE relid='".$_SESSION['uid']."'"); $notification_settings = mysqli_fetch_array($notification_settings); return $notification_settings; } ?> "now()", "description" => $description, "user" => $username, "relid" => $relid, "customer_relid"=>$customer_relid, "ipaddr" => $remote_ip)); } function toMySQLDate($date) { global $CONFIG; $day = substr($date, 8, 2); $month = substr($date, 5, 2); $year = substr($date, 0, 4); $hours = substr($date, 11, 2); $minutes = substr($date, 14, 2); $seconds = substr($date, 17, 2); if ($hours && !$seconds) { $seconds = "00"; } $date = $year . "-" . $month . "-" . $day; if ($hours) { $date .= " " . $hours . ":" . $minutes . ":" . $seconds; } return $date; } function fromMySQLDate($date, $time = "", $client = "", $zerodateval = "") { global $CONFIG; global $timeoffset; if (substr($date, 0, 10) == "0000-00-00" && $zerodateval) { return $zerodateval; } $year = substr($date, 0, 4); $month = substr($date, 5, 2); $day = substr($date, 8, 2); $hours = substr($date, 11, 2); $minutes = substr($date, 14, 2); $seconds = substr($date, 17, 2); if ($timeoffset) { $hours = $hours + $timeoffset; $new_time = mktime($hours, $minutes, $seconds, $month, $day, $year); $year = date("Y", $new_time); $month = date("m", $new_time); $day = date("d", $new_time); $hours = date("H", $new_time); $minutes = date("i", $new_time); $seconds = date("s", $new_time); } if ($client && $CONFIG['ClientDateFormat']) { if ($CONFIG['ClientDateFormat'] == "full") { $date = date("jS F Y", mktime(0, 0, 0, $month, $day, $year)); } else { if ($CONFIG['ClientDateFormat'] == "shortmonth") { $date = date("jS M Y", mktime(0, 0, 0, $month, $day, $year)); } else { if ($CONFIG['ClientDateFormat'] == "fullday") { $date = date("l, F jS, Y", mktime(0, 0, 0, $month, $day, $year)); } } } if ($time) { $date .= " (" . $hours . ":" . $minutes . ")"; } } else { $date = $CONFIG['DateFormat']; $date = str_replace("YYYY", $year, $date); $date = str_replace("MM", $month, $date); $date = str_replace("DD", $day, $date); if ($time) { $date .= " " . $hours . ":" . $minutes; } } return $date; } function validateDateInput($date) { $sqldate = toMySQLDate($date); $dateonly = explode(" ", $sqldate); $dateparts = explode("-", $dateonly[0]); list($year, $month, $day) = $dateparts; if (is_numeric($day) && is_numeric($month) && is_numeric($year)) { return checkdate($month, $day, $year); } return false; } function MySQL2Timestamp($datetime) { $val = explode(" ", $datetime, 2); $date = explode("-", $val[0]); if ($val[1]) { $time = explode(":", $val[1]); } else { $time = "00:00:00"; } return mktime($time[0], $time[1], $time[2], $date[1], $date[2], $date[0]); } function getTodaysDate($client = "") { return fromMySQLDate(date("Y-m-d"), 0, $client); } function xdecrypt($ckey, $string) { $string = base64_decode($string); $keys = array(); $c_key = base64_encode(sha1(md5($ckey))); $c_key = substr($c_key, 0, round(ord($ckey[0]) / 5)); $c2_key = base64_encode(md5(sha1($ckey))); $last = strlen($ckey) - 1; $c2_key = substr($c2_key, 1, round(ord($ckey[$last]) / 7)); $c3_key = base64_encode(sha1(md5($c_key) . md5($c2_key))); $mid = round($last / 2); $c3_key = substr($c3_key, 1, round(ord($ckey[$mid]) / 9)); $c_key = $c_key . $c2_key . $c3_key; $c_key = base64_encode($c_key); for ($i = 0; $i < strlen($c_key); $i++) { $keys[] = $c_key[$i]; } for ($i = 0; $i < strlen($string); $i++) { $id = $i % count($keys); $ord = ord($string[$i]); ord($keys[$id]); $ord = $ord xor ord($keys[$id]); $id++; $ord = $ord and ord($keys[$id]); ($ord = $ord) && ord($keys[$id]); $id++; $ord = $ord or ord($keys[$id]); ($ord = $ord) || ord($keys[$id]); $id++; $ord = $ord - ord($keys[$id]); $string[$i] = chr($ord); } return base64_decode($string); } if(!function_exists("encrypt_decrypt")) { function encrypt_decrypt($action, $string) { $output = false; $encrypt_method = "AES-256-CBC"; $secret_key = 'SBUCVDXFYGZJ3K4M5P7Q8RATBUCWEXFYH2J3K5N6P7R9SATCVDWEYGZH2J'; $secret_iv = '3K4M6P7Q8SATBUDWEXFZH2J3M5N6P8R9SAUCVDWEYGZH2K4M5N7Q8R9TBU'; // hash $key = hash('sha256', $secret_key); // iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning $iv = substr(hash('sha256', $secret_iv), 0, 16); if ( $action == 'encrypt' ) { $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv); $output = str_replace("=", "|", base64_encode($output)); } else if( $action == 'decrypt' ) { $output = openssl_decrypt(str_replace("=", "|", base64_decode($string)), $encrypt_method, $key, 0, $iv); } return $output; } } if (!function_exists('array_key_first')) { function array_key_first(array $arr) { foreach($arr as $key => $unused) { return $key; } return NULL; } } if(!function_exists("get_url_data")) { function get_url_data() { global $CONFIG; global $url_path; $arr = array(); $url_arr = explode("/", $_SERVER['REQUEST_URI']); foreach($url_arr as $url) { if($url != '') { $arr[] = $url; } } $count = array_search($url_path,$url_arr,true); $a['start'] = $count; $a['total'] = count($arr); $a['url'] = $arr; return $a; } } if(!function_exists('load_hooks')) { function load_hooks() { global $CONFIG; ob_start(); include_once(realpath(__DIR__ . DIRECTORY_SEPARATOR . "hookfunctions.php")); ob_end_clean(); } } if(!function_exists('system_settings')) { function system_settings() { $query = full_query("SELECT * FROM `tblconfiguration`"); while($res = mysqli_fetch_assoc($query)) { $a[$res['setting']] = $res['value']; } $a['template'] = 'Resellers'; return $a; } } ?>$key)); $data = mysqli_fetch_array($query); return htmlspecialchars_decode($data['value']); } } 0) { $sms_credits = getCredits(); $email_credits = getEmailCredits(); $remainingLimits = remainingLimits(); //$notification_settings = get_notification_settings(); $_SESSION['user'] = getuserdetails($_SESSION['uid']); $_SESSION['user']['sms_credits'] = number_format(($sms_credits['balance'] + $sms_credits['paidbalance']), 0); if($currentPackage['payment_reminders'] == 'Unlimited') { $_SESSION['user']['email_credits'] = '∞'; } else { $_SESSION['user']['email_credits'] = number_format(($email_credits['balance'] + $email_credits['paidbalance']), 0); } if(file_exists(ROOTDIR.'/uploads/user_uploads/'.$_SESSION['uid'].'_profilephoto.jpg')) { $_SESSION['user']['profilephoto'] = '../../../uploads/user_uploads/'.$_SESSION['uid'].'_profilephoto.jpg?nocache='.date('ymdhis'); }elseif(file_exists(ROOTDIR.'/uploads/user_uploads/'.$_SESSION['uid'].'_profilephoto.png')) { $_SESSION['user']['profilephoto'] = '../../../uploads/user_uploads/'.$_SESSION['uid'].'_profilephoto.png?nocache='.date('ymdhis'); }elseif(file_exists(ROOTDIR.'/uploads/user_uploads/'.$_SESSION['uid'].'_profilephoto.jpeg')) { $_SESSION['user']['profilephoto'] = '../../../uploads/user_uploads/'.$_SESSION['uid'].'_profilephoto.jpeg?nocache='.date('ymdhis'); }elseif(file_exists(ROOTDIR.'/uploads/user_uploads/'.$_SESSION['uid'].'_profilephoto.gif')) { $_SESSION['user']['profilephoto'] = '../../../uploads/user_uploads/'.$_SESSION['uid'].'_profilephoto.gif?nocache='.date('ymdhis'); }elseif(file_exists(ROOTDIR.'/uploads/user_uploads/'.$_SESSION['uid'].'_profilephoto.JPG')) { $_SESSION['user']['profilephoto'] = '../../../uploads/user_uploads/'.$_SESSION['uid'].'_profilephoto.JPG?nocache='.date('ymdhis'); } $_SESSION['user']['notification']['login'] = $notification_settings['login']; $_SESSION['user']['notification']['payment'] = $notification_settings['payment']; $_SESSION['user']['notification']['booking'] = $notification_settings['booking']; $_SESSION['user']['notification']['system'] = $notification_settings['system']; $_SESSION['user']['getstarted'] = $notification_settings['getstarted']; $_SESSION['user']['paymentreminders']['payment_reminders'] = $notification_settings['payment_reminders']; $_SESSION['user']['paymentreminders']['payment_day'] = get_payment_day($notification_settings['day']); $_SESSION['user']['paymentreminders']['payment_day_setting'] = $notification_settings['day']; $_SESSION['user']['paymentreminders']['payment_time'] = date('h:i A', strtotime($notification_settings['time'])); $_SESSION['user']['paymentreminders']['payment_time_setting'] = $notification_settings['time']; $_SESSION['user']['paymentreminders']['payment_sms_notification'] = $notification_settings['send_sms']; $_SESSION['user']['paymentreminders']['appointment_reminders'] = $notification_settings['appointment_reminders']; $_SESSION['user']['paymentreminders']['appointment_day'] = get_payment_day($notification_settings['appointment_day']); $_SESSION['user']['paymentreminders']['appointment_day_setting'] = $notification_settings['appointment_day']; $_SESSION['user']['paymentreminders']['appointment_time'] = date('h:i A', strtotime($notification_settings['appointment_time'])); $_SESSION['user']['paymentreminders']['appointment_time_setting'] = $notification_settings['appointment_time']; $_SESSION['user']['paymentreminders']['appointment_sms_notification'] = $notification_settings['sappointment_end_sms']; $_SESSION['user']['invoicing']['hasinvoicing'] = $notification_settings['hasinvoicing']; $_SESSION['user']['invoicing']['businessname'] = $notification_settings['businessname']; $_SESSION['user']['invoicing']['businessaddress'] = $notification_settings['businessaddress']; $_SESSION['user']['invoicing']['businesspostcode'] = $notification_settings['businesspostcode']; $_SESSION['user']['invoicing']['businessemail'] = $notification_settings['businessemail']; $_SESSION['user']['invoicing']['registrationnumber'] = $notification_settings['registrationnumber']; $_SESSION['user']['invoicing']['vatregistrationnumber'] = $notification_settings['vatregistrationnumber']; $query_brand = full_query("SELECT mod_brands.* FROM `mod_brands` LEFT JOIN tblclient_brands ON tblclient_brands.brandid=mod_brands.id WHERE tblclient_brands.relid = '".$_SESSION['uid']."' "); } else { //$_SERVER['PHP_SELF'] $query_brand = full_query("SELECT mod_brands.* FROM `mod_brands` LEFT JOIN tblclient_brands ON tblclient_brands.brandid=mod_brands.id WHERE mod_brands.brand_url = '".$_SERVER['HTTP_HOST']."' "); } if(mysqli_num_rows($query_brand) > 0) { $data = mysqli_fetch_array($query_brand); $_SESSION['brand_name'] = $data['brand_name']; $_SESSION['brand_logo'] = $data['brand_logo']; $_SESSION['logo_width'] = $data['logo_width']; $_SESSION['primary_col'] = $data['primary_col']; $_SESSION['secondary_col'] =$data['secondary_col']; $_SESSION['link_col'] = $data['link_col']; } else { $_SESSION['brand_name'] = $data['brand_logo']; $_SESSION['brand_logo'] = $data['brand_logo']; $_SESSION['logo_width'] = $data['logo_width']; $_SESSION['primary_col'] = $data['primary_col']; $_SESSION['secondary_col'] =$data['secondary_col']; $_SESSION['link_col'] = $data['link_col']; } } if(!function_exists('get_payment_day')) { function get_payment_day($id) { switch ($id) { case 0: return 'Every Day'; break; case 1: return 'Every Monday'; break; case 2: return 'Every Tuesday'; break; case 3: return 'Every Wednesday'; break; case 4: return 'Every Thursday'; break; case 5: return 'Every Friday'; break; case 6: return 'Every Saturday'; break; case 7: return 'Every Sunday'; break; } } } if(!function_exists('switch_theme')) { function switch_theme($group) { switch ($group) { case 0: return 'Portal'; break; case 1: return 'Development'; break; default: return 'Portal'; } } } if (!function_exists('get_client_ip')) { function get_client_ip() { $ipaddress = ''; if (getenv('HTTP_CLIENT_IP')) $ipaddress = getenv('HTTP_CLIENT_IP'); else if(getenv('HTTP_X_FORWARDED_FOR')) $ipaddress = getenv('HTTP_X_FORWARDED_FOR'); else if(getenv('HTTP_X_FORWARDED')) $ipaddress = getenv('HTTP_X_FORWARDED'); else if(getenv('HTTP_FORWARDED_FOR')) $ipaddress = getenv('HTTP_FORWARDED_FOR'); else if(getenv('HTTP_FORWARDED')) $ipaddress = getenv('HTTP_FORWARDED'); else if(getenv('REMOTE_ADDR')) $ipaddress = getenv('REMOTE_ADDR'); else $ipaddress = 'UNKNOWN'; return $ipaddress; } } if (!function_exists('create_page')) { function create_page($page_data) { global $CONFIG; global $defaulturl; global $install_path; global $currentPackage; global $rp; $ca = new ClientArea(); $ca->initPage($page_data['theme']); if(is_array($_SESSION['accounts'])) $ca->assign('numaccounts',count($_SESSION['accounts'])); $ca->assign('todaysdate', date("l jS F Y", strtotime('today GMT'))); $ca->assign('datetoday', date("d/m/Y")); $ca->assign('clientip', get_client_ip()); $ca->assign('useragent', $_SERVER['HTTP_USER_AGENT']); $ca->assign('currentpackage', $currentPackage); $ca->assign('nocache', date('ymdhis')); $notifications = header_get_notifications(); if(is_array($notifications)) $ca->assign('notifications', $notifications); $ca->assign("theme_folder", '//' . $_SERVER['HTTP_HOST'] . '/templates/' . $page_data['theme'] . '/'); if($install_path) { $ca->assign("rooturl", '//' . $_SERVER['HTTP_HOST'] . '/' . $install_path); } else { $ca->assign("rooturl", '//' . $_SERVER['HTTP_HOST'] . '/' ); } $ca->assign("editor", true); if (is_array($CONFIG)) { foreach ($CONFIG as $k => $v) { if ($k == 'HeaderCode') if ($v != '') $v = urldecode($v); if ($k == 'FooterCode') if ($v != '') $v = urldecode($v); $ca->assign($k, $v); } } if (is_array($page_data)) { foreach ($page_data as $a => $b) { if ($a == 'HeaderCode') if ($b != '') $b = urldecode($b); if ($a == 'FooterCode') if ($b != '') $b = urldecode($b); if ($a == 'title') $ca->assign('coursetitle', $b); $ca->assign('' . $a . '', $b); } } foreach ($_SESSION as $a => $b) { if ($a == 'HeaderCode') if ($b != '') $b = urldecode($b); if ($a == 'FooterCode') if ($b != '') $b = urldecode($b); if ($a == 'title') $ca->assign('coursetitle', $b); $ca->assign('' . $a . '', $b); } if (is_array($page_data['content'])) { foreach ($page_data['content'] as $a => $b) { if ($a == 'HeaderCode') if ($b != '') $b = urldecode($b); if ($a == 'FooterCode') if ($b != '') $b = urldecode($b); $ca->assign('' . $a . '', urldecode($b)); } } if ($_GET['error']) { $ca->assign("alert_message", create_alert_box($_GET['error'], 'danger')); } if ($_GET['warning']) { $ca->assign("alert_message", create_alert_box($_GET['warning'], 'warning')); } if ($_GET['success']) { $ca->assign("alert_message", create_alert_box($_GET['success'], 'success')); } $ca->assign("theme", $page_data['theme']); $ca->assign("themes_folder", "templates/".$page_data['theme']."/"); $ca->assign("rootdir_theme", ROOTDIR."/templates/".$page_data['theme']."/"); if ($page_data['type'] == '404') { http_response_code(404); $ca->setTemplate("404"); } else { if($rp) { $page_data['template'] = 'includes/'.$rp; } if(!$_POST['subaction'] == 'payOverdue') { $balance = get_overdue_data(); if(is_array($balance)) { if(count($balance) > 0) { $_GET['type'] = 'payinvoice'; $ca->assign('overdueInvoices', $balance['invoices']); $ca->assign('overdueTotal', $balance['total']); $page_data['template'] = 'myplan'; } } } if($_POST['subaction'] == 'payOverdue') { $balance = invoices_capture($_POST); if(is_array($balance)) { if(count($balance) > 0) { $_GET['type'] = 'payinvoice'; $ca->assign('haserror', true); $ca->assign('overdueInvoices', $balance['invoices']); $ca->assign('overdueTotal', $balance['total']); $page_data['template'] = 'myplan'; } } } if($_SESSION['user']['getstarted']) { $page_data['template'] = 'getstarted'; } if($rp) { $split = explode('/', $page_data['template']); $countsplit = count($split) - 1; $last_variable = $split[$countsplit]; unset($split[$countsplit]); $implode = implode("/",$split).'/php/'.$last_variable.'.php'; if (file_exists( ROOTDIR . '/templates/' . $page_data['theme'] . '/' . $implode)) { include(ROOTDIR . '/templates/' . $page_data['theme'] . '/' . $implode); } } else { if (file_exists('' . ROOTDIR . '/templates/' . $page_data['theme'] . '/php/' . $page_data['template'] . '.php')) { include('' . ROOTDIR . '/templates/' . $page_data['theme'] . '/php/' . $page_data['template'] . '.php'); } } $ca->assign("page_name", $page_data['template']); $ca->setTemplate($page_data['template']); } if($_POST['ajax']) { call_user_func($_POST['func'], $_POST); die(); } $ca->addOutputHookFunction("ClientAreaPageViewEmail"); $ca->output(); $_SESSION['error_login'] = ''; $_SESSION['error_resetpassword'] = ''; } } if (!function_exists('loadPage')) { function loadPage($theme) { global $CONFIG; global $install_path; global $currentPackage; global $rp; $currentPackage = get_product_details(); if($install_path) { $rooturl = '//' . $_SERVER['HTTP_HOST'] . '/' . $install_path; } else { $rooturl = '//' . $_SERVER['HTTP_HOST'] . '/' ; } $url_data = get_url_data(); $page_arr = array(); $count = $url_data['total']; $v = $url_data['url']; $rp = $_GET['rp']; if ($count ) { $count = $count; if ($v[$count] == $v[($count)]) { $number = '0'; $error = 1; } } else { $v[0] = 'front-page'; } if($v[0] == 'logout') { full_query("DELETE FROM tblclients_ios WHERE uuid='".$_SESSION['uuid']."'"); unset($_COOKIE['uuid']); unset($_COOKIE['onesignal_push_id']); destroy_login(); header('Location: '.$rooturl); } foreach($v as $u => $b) { if (preg_match('/\?\b/', $b)) { $check_page = explode("?", $b); if ($check_page[1]) { $count = $count - 1; $get = explode("&", $check_page[1]); foreach ($get as $g) { $h = explode("=", $g); $_GET[$h[0]] = $h[1]; } } } } if($_SERVER['HTTP_HOST'] == 'www.pay.pay-me.co.uk') { if($v[0] != 'paylink') { header('Location: https://www.pay-me.co.uk'); } } if($v[0] == 'paylink') { if($_SERVER['HTTP_HOST'] != 'www.pay.pay-me.co.uk') { if($v[0] == 'paylink') { header('Location: https://www.pay.pay-me.co.uk/paylink/?code='.$_GET['code']); } } if (file_exists('' . ROOTDIR . '/templates/' . $theme . '/' . $v[0] . '.tpl')) { $page_arr['id'] = ''; $page_arr['type'] = ''; $page_arr['url'] = ''; $page_arr['pagetitle'] = ucwords(str_replace("-", " ", $v['1'])) . ' - ' . $title[$current_lang]['course']['sitetitle']; $page_arr['title'] = ucwords(str_replace("-", " ", $v['1'])); $page_arr['meta'] = $title[$current_lang]['course']['sitetitle'] . ' ' . $res['page'] . ' Page'; $page_arr['template'] = $v[0]; $page_arr['page_name'] = $v[0]; $page_arr['theme'] = $theme; $request_arr = getPaymentScreen($_GET['code']); if($request_arr == 'false') { header('Location: /404/'); } $page_arr['header_request'] = $request_arr['request']; $page_arr['header_request']['user'] = getuserdetails($request_arr['request']['relid']); if(file_exists(ROOTDIR.'/uploads/user_uploads/'.$request_arr['request']['relid'].'_profilephoto.jpg')) { $page_arr['header_request']['user']['profilephoto'] = '../../../uploads/user_uploads/'.$request_arr['request']['relid'].'_profilephoto.jpg?nocache='.date('ymdhis'); }elseif(file_exists(ROOTDIR.'/uploads/user_uploads/'.$request_arr['request']['relid'].'_profilephoto.png')) { $page_arr['header_request']['user']['profilephoto'] = '../../../uploads/user_uploads/'.$request_arr['request']['relid'].'_profilephoto.png?nocache='.date('ymdhis'); }elseif(file_exists(ROOTDIR.'/uploads/user_uploads/'.$request_arr['request']['relid'].'_profilephoto.jpeg')) { $page_arr['header_request']['user']['profilephoto'] = '../../../uploads/user_uploads/'.$request_arr['request']['relid'].'_profilephoto.jpeg?nocache='.date('ymdhis'); }elseif(file_exists(ROOTDIR.'/uploads/user_uploads/'.$request_arr['request']['relid'].'_profilephoto.gif')) { $page_arr['header_request']['user']['profilephoto'] = '../../../uploads/user_uploads/'.$request_arr['request']['relid'].'_profilephoto.gif?nocache='.date('ymdhis'); }elseif(file_exists(ROOTDIR.'/uploads/user_uploads/'.$request_arr['request']['relid'].'_profilephoto.JPG')) { $page_arr['header_request']['user']['profilephoto'] = '../../../uploads/user_uploads/'.$request_arr['request']['relid'].'_profilephoto.JPG?nocache='.date('ymdhis'); } } else { $page_arr['id'] = ''; $page_arr['pagetitle'] = 'Page Not Found'; $page_arr['type'] = '404'; $page_arr['url'] = ''; $page_arr['title'] = '404 Not Found'; $page_arr['meta'] = '404 Not Found'; $page_arr['content'] = 'Not Found'; $page_arr['theme'] = $theme; } } else { if($_GET['uuid']) { if(!isset($_COOKIE['uuid'])) { setcookie('uuid', $_GET['uuid'], (time() + (86400 * 30) * 3650), "/"); setcookie('os', $_GET['os'], (time() + (86400 * 30) * 3650), "/"); setcookie('onesignal_push_id', $_GET['onesignal_push_id'], (time() + (86400 * 30) * 3650), "/"); } } if(!isset($_COOKIE['uuid'])) { } else { $_GET['uuid'] = $_COOKIE['uuid']; $_GET['onesignal_push_id'] = $_COOKIE['onesignal_push_id']; $_GET['os'] = $_COOKIE['os']; } if (!$_SESSION['uid']) { $find_uuid = full_query("SELECT * FROM tblclients_ios WHERE uuid='".$_GET['uuid']."'"); $uuid = mysqli_fetch_assoc($find_uuid); if($_GET['uuid']) { if(!$uuid['uuid']) { $_SESSION['uuid'] = $_GET['uuid']; } else { $_SESSION['uid'] = $uuid['relid']; if($_GET['onesignal_push_id']) { full_query("UPDATE tblclients_ios SET push_id='".$_GET['onesignal_push_id']."' WHERE id='".$uuid['id']."'"); } if($_SESSION['onesignal_push_id']) { full_query("UPDATE tblclients_ios SET push_id='".$_SESSION['onesignal_push_id']."' WHERE id='".$uuid['id']."'"); } $_SESSION['uuid'] = $uuid['uuid']; header('Location: ../../'); } } if($_GET['onesignal_push_id']) { if(!$uuid['onesignal_push_id']) { $_SESSION['onesignal_push_id'] = $_GET['onesignal_push_id']; } else { $_SESSION['onesignal_push_id'] = $uuid['onesignal_push_id']; header('Location: ../../'); } } $allowed_url = array('login', 'forgotpassword'); if($v[0] == 'front-page') $v[0] = 'login'; if(in_array($v[0], $allowed_url)) { check_invoice_page(); set_user_variables(); $theme = switch_theme($_SESSION['user']['groupid']); if (file_exists('' . ROOTDIR . '/templates/'.$theme.'/'.$v[0].'.tpl')) { $page_arr['id'] = ''; $page_arr['type'] = ''; $page_arr['url'] = ''; $page_arr['pagetitle'] = ucwords(str_replace("-", " ", $v['1'])) . ' - ' . $title[$current_lang]['course']['sitetitle']; $page_arr['title'] = ucwords(str_replace("-", " ", $v['1'])); $page_arr['meta'] = $title[$current_lang]['course']['sitetitle'] . ' ' . $res['page'] . ' Page'; $page_arr['template'] = $v[0]; $page_arr['page_name'] = $v[0]; $page_arr['theme'] = $theme; } } else { set_user_variables(); if (file_exists('' . ROOTDIR . '/templates/Portal/login.tpl')) { $page_arr['id'] = ''; $page_arr['type'] = ''; $page_arr['url'] = ''; $page_arr['pagetitle'] = ucwords(str_replace("-", " ", $v['1'])) . ' - ' . $title[$current_lang]['course']['sitetitle']; $page_arr['title'] = ucwords(str_replace("-", " ", $v['1'])); $page_arr['meta'] = $title[$current_lang]['course']['sitetitle'] . ' ' . $res['page'] . ' Page'; $page_arr['template'] = 'login'; $page_arr['page_name'] = 'login'; $page_arr['theme'] = 'Portal'; } } } else { set_user_variables(); $theme = switch_theme($_SESSION['user']['groupid']); if (preg_match('/\?\b/', $v[0])) { $v[0] = 'front-page'; } if(!$currentPackage['product']) { $v[0] = 'getstarted'; } if (file_exists('' . ROOTDIR . '/templates/' . $theme . '/' . $v[0] . '.tpl')) { $page_arr['id'] = ''; $page_arr['type'] = ''; $page_arr['url'] = ''; $page_arr['pagetitle'] = ucwords(str_replace("-", " ", $v['1'])) . ' - ' . $title[$current_lang]['course']['sitetitle']; $page_arr['title'] = ucwords(str_replace("-", " ", $v['1'])); $page_arr['meta'] = $title[$current_lang]['course']['sitetitle'] . ' ' . $res['page'] . ' Page'; $page_arr['template'] = $v[0]; $page_arr['page_name'] = $v[0]; $page_arr['theme'] = $theme; } else { $page_arr['id'] = ''; $page_arr['pagetitle'] = 'Page Not Found'; $page_arr['type'] = '404'; $page_arr['url'] = ''; $page_arr['title'] = '404 Not Found'; $page_arr['meta'] = '404 Not Found'; $page_arr['content'] = 'Not Found'; $page_arr['theme'] = $theme; } } } return $page_arr; } } ?>$code)); if(mysqli_num_rows($query) > 0) { $data = mysqli_fetch_array($query); $request = full_query("SELECT tblclients_customers.*, tblclient_requests.*, tblclients_customers.id as userid FROM tblclient_requests LEFT JOIN tblclients_customers ON tblclients_customers.id = tblclient_requests.customer_relid WHERE tblclient_requests.`id`='".$data['id']."'"); $request_data = mysqli_fetch_array($request); $request_data['multirequest'] = json_decode($request_data['multirequest'], true); $arr['request'] = $request_data; if($gateway) { $arr['gateway_settings'] = get_active_gateways($data['relid'], $gateway); } else { $arr['gateways'] = get_active_gateways($data['relid'], '', true); } return $arr; } else { return 'false'; } } ?>'.($newyear).''; } return $return; } function filter_months_options($id = NULL) { for ($x = 1; $x <= 12; $x++) { $month = sprintf("%02d", $x); $selected=''; if($id == $month) $selected='selected="selected"'; $return .= ''; } return $return; }$userid), "setting", "ASC"); while ($data = mysqli_fetch_array($result)) { $gwv_gateway = $data["gateway"]; $gwv_setting = $data["setting"]; $gwv_value = $data["value"]; $GatewayValues[$gwv_gateway][$gwv_setting] = $gwv_value; } $includedmodules = array(); $dh = opendir(ROOTDIR."/includes/modules/gateways/"); while (false !== ($file = readdir($dh))) { $fileext = explode(".", $file, 2); if (trim($file) && $file != "index.php" && 1 < count($fileext) && $fileext[1] == "php" && !in_array($fileext[0], $includedmodules)) { $includedmodules[] = $fileext[0]; $gwv_modulename = $fileext[0]; //echo $gwv_modulename.''; require_once ROOTDIR . "/includes/modules/gateways/" . $gwv_modulename . ".php"; //echo ' - Included
'; $AllGateways[] = $gwv_modulename; ; if (isset($GatewayValues[$gwv_modulename]["type"])) { $ActiveGateways[] = $gwv_modulename; } else { $DisabledGateways[] = $gwv_modulename; } if (function_exists($gwv_modulename . "_config")) { $GatewayConfig[$gwv_modulename] = call_user_func($gwv_modulename . "_config"); } else { $GatewayFieldDefines = array(); $GatewayFieldDefines["FriendlyName"] = array("Type" => "System", "Value" => $GATEWAYMODULE[$gwv_modulename . "visiblename"]); if (isset($GATEWAYMODULE[$gwv_modulename . "notes"])) { $GatewayFieldDefines["UsageNotes"] = array("Type" => "System", "Value" => $GATEWAYMODULE[$gwv_modulename . "notes"]); } call_user_func($gwv_modulename . "_activate"); $GatewayConfig[$gwv_modulename] = $GatewayFieldDefines; } } } if($selected_gateway) { $result = select_query("tbl_client_paymentgateways", "", array("gateway"=>$selected_gateway), "setting", "ASC"); while ($data = mysqli_fetch_array($result)) { $gwv_gateway = $data["gateway"]; $gwv_setting = $data["setting"]; $gwv_value = $data["value"]; $GatewayValues[$gwv_gateway][$gwv_setting] = $gwv_value; } return $GatewayValues; } sort($AllGateways); $output = array(); foreach ($AllGateways as $modulename) { $result = select_query("tbl_client_paymentgateways", "", array("gateway"=>$modulename), "setting", "ASC"); while ($data = mysqli_fetch_array($result)) { $gwv_gateway = $data["gateway"]; $gwv_setting = $data["setting"]; $gwv_value = $data["value"]; $GatewayValues[$gwv_gateway][$gwv_setting] = $gwv_value; } $displayName = $GatewayConfig[$modulename]["FriendlyName"]["Value"]; $isActive = in_array($modulename, $ActiveGateways); $btnDisabled = $isActive ? " disabled" : ""; // btnActivate-" . $modulename . " if($isActive) { if($isarr) { $activeoutput[$modulename] = $GatewayValues[$modulename]['name']; } else { $link = '/paylink/?code='.$_GET['code'].'&gateway='.$modulename; $activeoutput[strtolower($displayName)] = "
  • " . $GatewayValues[$modulename]['name'] . "\n

  • "; } } } ksort($activeoutput); ksort($output); if($isarr) { return $activeoutput; } $module_list = implode($output); $active_module_list = implode($activeoutput); return $active_module_list; } $val) { $oldnot[$old] = 0; } update_query('tblclient_notification_settings', $oldnot, array("relid"=>$userid)); foreach($notif as $k => $v) { $notifications[$k] = 1; } update_query('tblclient_notification_settings', $notifications, array("relid"=>$userid)); } function update_profile($v) { $results = localAPI('UpdateClient', $v['user']); return $results; } function update_profile_password($userid, $password) { $url = 'https://admin.paymyservices.com/modules/addons/ChangePassword/aJax_changePW.php'; $values['userid'] = $userid; $values['pass'] = $password; // Call the API $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_TIMEOUT, 30); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($values)); $response = curl_exec($ch); if (curl_error($ch)) { die('Unable to connect: ' . curl_errno($ch) . ' - ' . curl_error($ch)); } curl_close($ch); return $response; } $userid, "currency" => 'GBP', "gateway" => $gateway, "date" => $date, "description" => $description, "amountin" => $amountin, "transid" => $transid, "requestid" => $requestid, "iscompleted" => 1); $saveid = insert_query("tblclient_accounts", $array); $array["id"] = $saveid; markrequest_paid($requestid, $userid, 'paycode', true); run_hook("AddTransaction", $array); } function addInvoicePayment($paycode, $transid, $amount, $gateway, $noemail = "", $date = "") { $result = select_query("tblclient_requests", "relid,customer_relid,amount,status", array("paycode" => $paycode)); $data = mysqli_fetch_array($result); $userid = $data["relid"]; $total = $data["amount"]; $status = $data["status"]; if ($status == "Cancelled") { return false; } if ($status == "Paid") { return false; } $result = select_query("tblclient_accounts", "SUM(amount)", array("requestid" => $paycode)); $data = mysqli_fetch_array($result); $amountpaid = $data[0]; $balance = $total - $amountpaid; if (!$amount) { $amount = $balance; if ($amount <= 0) { return false; } } addtransaction($userid, 0, "Invoice Payment", $amount, $gateway, $transid, $paycode, $date); run_hook("AddInvoicePayment", array("requestid" => $paycode)); if (!$noemail) { //sendMessage("Invoice Payment Confirmation", $paycode); } }getMajor(), WHMCS\Module\Gateway\Stripe\Constant::$appUrl, WHMCS\Module\Gateway\Stripe\Constant::$appPartnerId); Stripe\Stripe::setApiKey($params["secretKey"]); } function add_customer_to_stripe($v) { stripe_start_stripe($v); $paymentMethodId = $v['paymentMethodId']; $stripeCustomer = null; $client = null; $method = null; $billingContact = null; if ($paymentMethodId) { try { $method = \Stripe\PaymentMethod::retrieve($paymentMethodId); if ($method->customer) { $stripeCustomer = \Stripe\Customer::retrieve($method->customer); } } catch (\Exception $e) { } } $clientId = $_SESSION['uid']; if ($client && !$stripeCustomer) { } } function deletePaymentMethod($v) { $command = 'DeletePayMethod'; $postData = array( 'clientid' => $_SESSION['uid'], 'paymethodid' => $v['paymethodid'], ); $adminUsername = ''; $results = localAPI($command, $postData, $adminUsername); //print_r($results); header('Location: ../../../../paymentmethods/'); } function addPaymentMethod($v) { $command = 'AddPayMethod'; $postData = array( 'clientid' => $_SESSION['uid'], 'type' => 'CreditCard', 'description' => $v['description'], 'card_number' => $v['ccnumber'], 'card_expiry' => $v['expirydate'], ); $adminUsername = ''; // Optional for WHMCS 7.2 and later $results = localAPI($command, $postData, $adminUsername); header('Location: ../paymentmethods/'); } function listPaymentMethods() { $command = 'GetPayMethods'; $postData = array( 'clientid' => $_SESSION['uid'] ); $adminUsername = ''; // Optional for WHMCS 7.2 and later $results = localAPI($command, $postData, $adminUsername); if (count($results['paymethods']) > 0) { foreach($results['paymethods'] as $res) { $arr[$res['id']]['id'] = $res['id']; $arr[$res['id']]['card_last_four'] = $res['card_last_four']; $arr[$res['id']]['expiry_date'] = $res['expiry_date']; $arr[$res['id']]['card_type'] = $res['card_type']; $arr[$res['id']]['type'] = $res['type']; } } return $arr; }$invoiceid, "status"=>"Unpaid")); if(mysqli_num_rows($find_invoice_status) > 0) { $capturePayment = capture_payment($invoiceid); if($capturePayment['result'] == 'success') { $success = true; } else { $success = false; $unpaidinvoices[] = $invoiceid; } } } if(!$success) { return get_overdue_data(); } return ''; } function get_overdue_data() { $total = 0; $invoices = check_overdue_invoices(); if(is_array($invoices)) { if(count($invoices) > 0) { foreach($invoices as $invoice) { $url[] = $invoice['id']; $total += $invoice['total']; } $returnurl['invoices'] = implode(",", $url); $returnurl['total'] = $total; } } return $returnurl; } function check_overdue_invoices() { $query = full_query('SELECT * FROM tblinvoices WHERE status="Unpaid" AND userid="'.$_SESSION['uid'].'" AND NOW() >= duedate'); if(mysqli_num_rows($query) > 0) { while($res = mysqli_fetch_assoc($query)) { $arr[$res['id']]['id'] = $res['id']; $arr[$res['id']]['total'] = $res['total']; } return $arr; } } function check_invoice_page() { global $install_path; if($install_path) { $rooturl = '//' . $_SERVER['HTTP_HOST'] . '/' . $install_path; } else { $rooturl = '//' . $_SERVER['HTTP_HOST'] . '/' ; } if($_GET['p1'] == 'invoices') { if($_GET['p4']) { $_SESSION['invoicelogin'] = true; $userid = $_GET['p2']; $invoiceid = $_GET['p3']; if($_GET['p4'] == 'qeGH65FGH') { // BT Login $_SESSION['uid'] = $userid; $_SESSION['nsb'] = ''; if($_GET['p5']) { header('Location: ../'); } } elseif($_GET['p4'] == 'aCh5GefD') { // BE Login $_SESSION['uid'] = $userid; $_SESSION['nsb'] = true; if($_GET['p5']) { header('Location: ../'); } } else { header('Location: '.$rooturl); } } else { if(!$_SESSION['uid']) { header('Location: '.$rooturl); } } } else { if($_SESSION['invoicelogin']) { destroy_login(); } } } function payinvoice_paypal($v) { global $CONFIG; $invoice_url = urlencode($CONFIG['rooturl'].'invoices/'.$_SESSION['uid'].'/'.$v['invoice']); $return_url = urlencode($CONFIG['rooturl'].'invoices/'.$_SESSION['uid'].'/'.$v['invoice']); $notify = urlencode('https://www.portal.mybigsky.co.uk/functions/paypal_ipn.php'); $paypalemail = 'accounts@victoriaarpels.com'; $paypal_url = 'https://www.paypal.com/cgi-bin/webscr?business='.$paypalemail.'&cmd=_xclick¤cy_code=GBP&amount='.$v['amount'].'&item_name='.$v['invoice'].'&no_note=1&no_shipping=1&charset=utf-8¤cy_code=GBP&custom='.$v['invoice'].'&rm=2&return='.$return_url.'&cancel_return='.$invoice_url.'¬ify_url='.$notify; header("Location: ".$paypal_url); } function create_sso_token($destination) { if(!$_SESSION['uid']) { $uid = $_GET['p2']; } else { $uid = $_SESSION['uid']; } $command = 'CreateSsoToken'; $postData = array( 'client_id' => $uid, 'destination' => 'sso:custom_redirect', 'sso_redirect_path' => $destination, ); $adminUsername = 'ADMIN_USERNAME'; // Optional for WHMCS 7.2 and later $results = localAPI($command, $postData, $adminUsername); return $results; } function autoLogin($email, $invoiceid) { $whmcsurl = "https://billing.mybigsky.co.uk/dologin.php"; $autoauthkey = "zcDOyyJN05QI@"; $timestamp = time(); # Get current timestamp $goto = "dl.php?type=i&id=" . $invoiceid; //$hash = sha1($email . $timestamp . $autoauthkey); # Generate Hash # Generate AutoAuth URL & Redirect $url = $whmcsurl . "?email=$email×tamp=$timestamp&hash=$hash&goto=" . urlencode($goto); $results = create_sso_token($goto); return $results['redirect_url'].'='.$results['access_token']; //header("Location: $url"); } function autoLoginGoTo($email, $url) { $explode = explode('?', $url); if($explode[0] == 'creditcard.php') { $explode2 = explode('=', $explode[1]); $invoiceid = $explode2[1]; full_query("UPDATE tblinvoices SET paymentmethod='paypalpaymentspro' WHERE id='".$invoiceid."'"); } $goto = "viewinvoice.php?id=$invoiceid"; $results = create_sso_token($goto); return $results['redirect_url'].'='.$results['access_token']; //header("Location: $url"); } function get_invoice($id) { $query = full_query('SELECT tblinvoices.*, tblorders.id as orderid FROM tblinvoices LEFT JOIN tblorders on tblorders.invoiceid = tblinvoices.id WHERE tblinvoices.id="' . $id . '"'); while ($res = mysqli_fetch_assoc($query)) { $arr[] = $res; } $a = $arr[0]; foreach($a as $k => $v) { if($k == 'date') { $a['date'] = date("jS F Y", strtotime($v)); } if($k == 'duedate') { $a['duedate'] = date("jS F Y", strtotime($v)); } } return $a; } function getInvoiceDetails($invoicenum) { $id = $invoicenum; $query = full_query('SELECT * FROM tbl_invoice_data WHERE invoiceid="' . $id . '"'); while ($res = mysqli_fetch_assoc($query)) { $arr[] = $res; } $a = $arr[0]; return $a; } function loopInvoice($id) { $query = full_query("SELECT * FROM `tblinvoiceitems` WHERE `invoiceid` = '" . $id . "' AND `userid` = '" . $_SESSION['uid'] . "' "); if (mysqli_num_rows($query) > 0) { while ($res = mysqli_fetch_assoc($query)) { $arr[$res['id']]['title'] = nl2br(stripslashes(str_replace("Day/s", "Day's", $res['description']))); $arr[$res['id']]['total'] = $res['amount']; } return $arr; } else { return 'error'; } } function listAccountInvoices() { $query = full_query("SELECT tblinvoices.*, tblorders.id as orderid FROM tblinvoices LEFT JOIN tblorders on tblorders.invoiceid = tblinvoices.id WHERE tblinvoices.userid = '" . $_SESSION['uid'] . "' ORDER BY status DESC"); if (mysqli_num_rows($query) > 0) { while ($res = mysqli_fetch_assoc($query)) { $arr[$res['id']]['id'] = $res['id']; $arr[$res['id']]['status'] = $res['status']; $arr[$res['id']]['subtotal'] = $res['subtotal']; $arr[$res['id']]['tax'] = $res['tax']; $arr[$res['id']]['total'] = $res['total']; $arr[$res['id']]['taxrate'] = $res['taxrate']; $arr[$res['id']]['duedate'] = $res['duedate']; $arr[$res['id']]['date'] = date("jS F Y", strtotime($res['date'])); $arr[$res['id']]['orderid'] = $res['orderid']; } } return $arr; } ?>setApiKey('api-key', SIBAPIKEY); $apiInstance = new SendinBlue\Client\Api\TransactionalSMSApi( // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. // This is optional, `GuzzleHttp\Client` will be used as default. new GuzzleHttp\Client(), $config ); $sendTransacSms = new \SendinBlue\Client\Model\SendTransacSms(); $sendTransacSms['sender'] = $v['sender']; $sendTransacSms['recipient'] = $v['recipient']; $sendTransacSms['content'] = $v['message']; $sendTransacSms['type'] = 'transactional'; try { $result = $apiInstance->sendTransacSms($sendTransacSms); $a=json_encode((array)$result); $b=(array)json_decode(str_replace('\u0000*\u0000','',$a)); $reference = $b['container']->reference; $messageid = $b['container']->messageId; update_query("tblclients_sms_history_send", array("messageid"=>$messageid,"reference"=>$reference), array("id"=>$v['insertid'])); logActivity("SMS Sent to " . $v['recipient'] . " (" . $v['message'] . ") ", $v['userid'], $v['customerid']); return 'success'; } catch (Exception $e) { return 'error'; } } function send_SMS($v) { $get_credits = getCredits('', $v['userid']); $total_credits = number_format(($get_credits['balance'] + $get_credits['paidbalance']), 0); if($total_credits == 0) { logActivity("No SMS Credits", $v['userid'], $v['customerid']); return 'nocredits'; } else { $smslength = strlen($v['message']); $insert = array("relid"=>$v['userid'],"customerid"=>$v['customerid'],"message"=>$v['message'], "datetime"=>"now()"); if($v['appointmentid']) $insert['appointmentid'] = $v['appointmentid']; if($v['requestid']) $insert['requestid'] = $v['requestid']; $insertid = insert_query("tblclients_sms_history_send", $insert); $v['insertid'] = $insertid; $v['sms_length'] = $smslength; $v['sms_credits'] = round($smslength/160); $deductsms = deduct_SMS($v); if($deductsms == 'nocredits') { return 'nocredits'; } return fire_SMS($v); } } function compile_SMS($v) { $message_data = get_template_content($v['userid'], 'sms', $v['smsname']); $get_customer = select_query("tblclients_customers", "*", array("relid"=>$v['userid'], "id"=>$v['customerid'])); $data_customer = mysqli_fetch_array($get_customer); $get_sender = select_query("tblclients", "*", array("id"=>$v['userid'])); $data_sender = mysqli_fetch_array($get_sender); $v['recipient'] = "44".substr($data_customer['phonenumber'],1); $v['sender'] = "44".substr($data_sender['phonenumber'],1); if($v['appointmentid']) { $message = $message_data['message']; $find_appointment = select_query("tblclients_appointments", "*", array("id"=>$v['appointmentid'],"relid"=>$v['userid'],"customer_relid"=>$v['customerid'])); $data_appointment = mysqli_fetch_array($find_appointment); $v['appointmentid'] = $v['appointmentid']; $before = array("{client_first_name}","{date}","{time}"); $after = array($data_customer['firstname'], date("d/m/Y",strtotime($data_appointment['datetime'])),date("H:i",strtotime($data_appointment['datetime']))); $v['message'] = str_replace($before, $after, $message); } if($v['requestid']) { $v['requestid'] = $v['requestid']; $message = $message_data['message']; $before = array("{client_first_name}","{paycode}"); $after = array($data_customer['firstname'], $v['paycode']); $v['message'] = str_replace($before, $after, $message); } return $v; } function deduct_SMS($v) { $minimumNeeded = 1; $get_credits = getCredits('', $v['userid']); $total_credits = number_format(($get_credits['balance'] + $get_credits['paidbalance']), 0); if($v['sms_credits'] > 1) { $minimumNeeded = $v['sms_credits']; } if($total_credits < $minimumNeeded) { logActivity("No SMS Credits", $v['userid'], $v['customerid']); return 'nocredits'; } else { if($get_credits['balance'] > $minimumNeeded) { $freeCredits = $get_credits['balance'] - $minimumNeeded; $paidCredits = $get_credits['paidbalance']; } else { $paidCredits = $get_credits['paidbalance'] - $minimumNeeded; $freeCredits = "0"; } update_query("tblclients_smscredits", array("paidbalance"=>$paidCredits,"balance"=>$freeCredits),array("relid"=>$v['userid'])); logActivity("SMS New Balance - Paid: ".$paidCredits.", Free: ".$freeCredits, $v['userid'], $v['customerid']); } } function reset_SMSCredits($v) { if($v['bundle'] > 0) { $find = mysqli_num_rows(select_query("tblclients_smscredits", "*", array("relid"=>$_SESSION['uid']))); if($find == 0) { insert_query("tblclients_smscredits", array("balance"=>$v['emailbundle'], "relid"=>$_SESSION['uid'])); } else { update_query("tblclients_smscredits", array("balance"=>$v['bundle']),array("relid"=>$_SESSION['uid'])); } } } function topup_SMS($v) { if($v['bundle'] > 0) { $get_credits = getCredits('', $v['userid']); $current_credits = number_format(($get_credits['paidbalance']), 0); $insert_history = array( "relid" => $_SESSION['uid'], "sms" => $v['bundle'], "requestid" => $v['orderid'], "oldbalance" => $current_credits, "newbalance" => number_format(($current_credits + $v['bundle']), 0), "datetime" => "now()" ); insert_query("tblclients_sms_history", $insert_history); update_query("tblclients_smscredits", array("paidbalance"=>($get_credits['paidbalance']+$v['bundle'])),array("relid"=>$_SESSION['uid'])); } } function getCredits($find = NULL, $userid = NULL) { if($userid) { $sms_credits = select_query("tblclients_smscredits", "*", array("relid" => $userid)); } else { $sms_credits = select_query("tblclients_smscredits", "*", array("relid" => $_SESSION['uid'])); } if($find) { if(mysqli_num_rows($sms_credits) > 0) { return 'found'; } else { return 'notfound'; } } $sms_credits = mysqli_fetch_array($sms_credits); return $sms_credits; } function buySMS($v) { if($v['bundle'] == '50') { $pid = '5'; }elseif($v['bundle'] == '100') { $pid = '6'; }elseif($v['bundle'] == '200') { $pid = '7'; } $order = api_AddOrder($pid); $invoiceid = $order['invoiceid']; $orderid = $order['orderid']; $capture = api_CapturePayment($invoiceid); if($capture['result'] == 'success') { return array("result"=>'success', "invoiceid"=>$invoiceid, "orderid"=>$orderid, "bundle"=>$v['bundle']); } else { return array("result"=>'error', "invoiceid"=>$invoiceid, "orderid"=>$orderid, "bundle"=>$v['bundle']); } } 0) { $find = mysqli_num_rows(select_query("tblclients_emailcredits", "*", array("relid"=>$_SESSION['uid']))); if($find == 0) { insert_query("tblclients_emailcredits", array("balance"=>$v['emailbundle'], "relid"=>$_SESSION['uid'])); } else { update_query("tblclients_emailcredits", array("balance"=>$v['emailbundle']),array("relid"=>$_SESSION['uid'])); } } } function topup_Email($v) { if($v['bundle'] > 0) { $get_credits = getEmailCredits('', $v['userid']); $current_credits = number_format(($get_credits['paidbalance']), 0); $insert_history = array( "relid" => $_SESSION['uid'], "sms" => $v['bundle'], "requestid" => $v['orderid'], "oldbalance" => $current_credits, "newbalance" => number_format(($current_credits + $v['bundle']), 0), "datetime" => "now()" ); insert_query("tblclients_email_history", $insert_history); update_query("tblclients_emailcredits", array("paidbalance"=>($get_credits['paidbalance']+$v['bundle'])),array("relid"=>$_SESSION['uid'])); } } function getEmailCredits($find = NULL, $userid = NULL) { if($userid) { $email_credits = select_query("tblclients_emailcredits", "*", array("relid" => $userid)); } else { $email_credits = select_query("tblclients_emailcredits", "*", array("relid" => $_SESSION['uid'])); } if($find) { if(mysqli_num_rows($email_credits) > 0) { return 'found'; } else { return 'notfound'; } } $email_credits = mysqli_fetch_array($email_credits); return $email_credits; } function deduct_Email($v) { $minimumNeeded = 1; $get_credits = getEmailCredits('', $v['userid']); $total_credits = number_format(($get_credits['balance'] + $get_credits['paidbalance']), 0); if($total_credits < $minimumNeeded) { logActivity("No Email Credits", $v['userid'], $v['customerid']); return 'nocredits'; } else { if($get_credits['balance'] > $minimumNeeded) { $freeCredits = $get_credits['balance'] - $minimumNeeded; $paidCredits = $get_credits['paidbalance']; } else { $paidCredits = $get_credits['paidbalance'] - $minimumNeeded; $freeCredits = "0"; } update_query("tblclients_emailcredits", array("paidbalance"=>$paidCredits,"balance"=>$freeCredits),array("relid"=>$v['userid'])); logActivity("Email New Balance - Paid: ".$paidCredits.", Free: ".$freeCredits, $v['userid'], $v['customerid']); } } function buyEmail($v) { if($v['bundle'] == '500') { $pid = '8'; }elseif($v['bundle'] == '1000') { $pid = '9'; }elseif($v['bundle'] == '2000') { $pid = '10'; } $order = api_AddOrder($pid); $invoiceid = $order['invoiceid']; $orderid = $order['orderid']; $capture = api_CapturePayment($invoiceid); if($capture['result'] == 'success') { return array("result"=>'success', "invoiceid"=>$invoiceid, "orderid"=>$orderid, "bundle"=>$v['bundle']); } else { return array("result"=>'error', "invoiceid"=>$invoiceid, "orderid"=>$orderid, "bundle"=>$v['bundle']); } } 0) { $data_cancel = mysqli_fetch_array($find_cancel); $arr[$res['id']]['cancelrequest'] = true; $arr[$res['id']]['cancelid'] = $data_cancel['id']; $arr[$res['id']]['cancelreason'] = $data_cancel['reason']; } $arr[$res['id']]['pid'] = $pid; $arr[$res['id']]['product'] = $res['product']; $arr[$res['id']]['group'] = $res['groupid']; $arr[$res['id']]['productid'] = $res['id']; $arr[$res['id']]['monthlycost'] = $res['monthly']; $arr[$res['id']]['upgradeurl'] = '/myplan/?type=upgrade&id='.$res['id']; if($userpid == $res['id']) { $arr[$res['id']]['currentplan'] = true; } else { $arr[$res['id']]['currentplan'] = false; } foreach($fields as $k => $v) { $arr[$res['id']][$k] = $v; } } return $arr; } function get_product_details() { $query = full_query("SELECT tblproducts.name as product, tblproducts.gid, tblproducts.gid as groupid, tblhosting.* FROM `tblhosting` LEFT JOIN tblproducts ON tblproducts.id = tblhosting.packageid WHERE tblhosting.`userid` = '".$_SESSION['uid']."' AND tblhosting.domainstatus='Active' AND tblproducts.gid='1'"); if(mysqli_num_rows($query) > 0) { while($res= mysqli_fetch_assoc($query)) { $pid = $res['packageid']; $get_fieldid = full_query("SELECT * FROM `tblcustomfields` WHERE `relid` = '$pid' AND type='Product'"); while($res2 = mysqli_fetch_assoc($get_fieldid)) { $fields[strtolower(str_replace(" ", "_", $res2['fieldname']))] = $res2['fieldoptions'];; } $find_cancel = full_query("SELECT * FROM `tblcancelrequests` WHERE `relid` = '".$res['id']."'"); if(mysqli_num_rows($find_cancel) > 0) { $data_cancel = mysqli_fetch_array($find_cancel); $arr['cancelrequest'] = true; $arr['cancelid'] = $data_cancel['id']; $arr['cancelreason'] = $data_cancel['reason']; } $arr['pid'] = $pid; $arr['product'] = $res['product']; $arr['group'] = $res['groupid']; $arr['hostingid'] = $res['id']; $arr['monthlycost'] = $res['amount']; foreach($fields as $k => $v) { $arr[$k] = $v; } } } else { } return $arr; } $hostingid, 'paymentmethod' => 'braintree', 'newproductbillingcycle' => 'monthly', 'type' => 'product', 'newproductid' => $v['id'] ); $adminUsername = ''; // Optional for WHMCS 7.2 and later $results = localAPI($command, $postData, $adminUsername); return $results; } function cancel_subscription($v) { $command = 'AddCancelRequest'; $postData = array( 'serviceid' => $v['serviceid'], 'type' => 'End of Billing Period', 'reason' => $v['reason'] ); $adminUsername = ''; // Optional for WHMCS 7.2 and later $results = localAPI($command, $postData, $adminUsername); update_query("tblinvoices",array("status"=>"Cancelled"),array("userid"=>$_SESSION['uid'],"stauts"=>"Unpaid")); return $results; } '; $calendar .= build_calendar($month,$year,$dateArray,$selected_date).''; return $calendar; } function get_days($month, $year, $selected_day) { $months = array("", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"); $month = (int) $month; $year = (int) $year; if (!$month) { $month = date("m"); } if (!$year) { $year = date("Y"); } $currentmonth = $months[(int) $month]; $currentyear = $year; $month = str_pad($month, 2, "0", STR_PAD_LEFT); if(!$selected_day) { if(date('Y-m') == $year.'-'.$month) { $selected_day = date('Y-m-d'); } else { $selected_day = date(''.$year.'-'.$month.'-01'); } } //echo $selected_day; $numberdays = date("t", strtotime($year.'-'.$month)); $appointments = get_appointments('', '', '', $month); foreach($appointments as $appointment) { $check_appointment[] = $appointment['day']; } for ($x = 1; $x <= $numberdays; $x++) { $select_class = ''; $this_day = date(''.$year.'-'.$month.'-'.sprintf("%02d", $x)); if($selected_day == $this_day) { $select_class = 'mbsc-selected'; } $hasappointment= ''; if(in_array($x, $check_appointment)) { $hasappointment = 'style="background:#ff0000"'; } $today = date('Y-m-d'); if($this_day == $today) { $select_class = 'mbsc-selected'; $scroll_day = $today; } // For selected = mbsc-selected $days .= '
    '.date("D", strtotime($this_day)).'
    '.$x.'
    '; } $days .= ' '; return $days; } function build_calendar($month,$year,$dateArray,$selected_date) { $formatmonth = date('F', strtotime($year.'-'.$month)); $days = get_days($month, $year, $selected_date); if(date('Y-m') == $year.'-'.$month) { $selected_date = date('Y-m-d'); } else { $selected_date = date($year.'-'.$month.'-01'); } $prevMonth = build_previousMonth($month,$year); $nextMonth = build_nextMonth($month,$year); $selected_date_sql = $selected_date; $selected_date = date("D j F Y", strtotime($selected_date)); $events = get_cal_events($selected_date_sql); $nocache = date('ymdhis'); $list_years = array("2022","2023","2024","2025","2026","2027","2028","2029","2030"); $list_months = array("01"=>"January","02"=>"February","03"=>"March","04"=>"April","05"=>"May","06"=>"June","07"=>"July","08"=>"August","09"=>"September","10"=>"October","11"=>"November","12"=>"December"); foreach($list_months as $month_key => $month_val) { $selected = ''; if(str_replace(" ", "", $month) == $month_key) $selected=' selected="selected"'; $option_month .= ''; } foreach($list_years as $year_key) { $selected = ''; if($year == $year_key) $selected=' selected="selected"'; $option_year .= ''; } $month_text = $list_months[$month]; $calendar = << $( document ).ready(function() { $(".day_select").on("click", function () { var date = $(this).data('date'); var friendly = $(this).data('friendly'); $(".day_select").removeClass("mbsc-selected"); $("#day_conatiner_"+date).addClass("mbsc-selected"); $("#friendly_date_container").html(friendly); $('#selecteddate').val(date); loadEvents(); }); }); function loadMonth() { var month = $('#selectmonth').val(); var year = $('#selectyear').val(); window.location.href="../../schedule/?month="+month+"&year="+year; } function loadEvents() { $('.events_container').html(''); $.get("../../schedule/", "ajax=true&subaction=events&date="+$("#selecteddate").val()+"&nocache={$nocache}", function (data) { $('.events_container').html(data); }); } function loadAppointment(title, link) { const request = []; request["message"] = "modal"; request["title"] = title; request["link"] = link; parent.postMessage(request,"https://application.pay-me.co.uk/"); } function newAppointment() { url = '/appointments/?action=new&date='+$('#selecteddate').val(); //loadIframeModal('New Appointment', url) const request = []; request["message"] = "modal"; request["title"] = "New Appointment"; request["link"] = url; parent.postMessage(request,"https://application.pay-me.co.uk/"); }
    {$month_text}, {$year}
    {$days}
    {$selected_date}
    {$events}
    EOF; return $calendar; } function get_cal_events($date, $month = NULL) { if(!$month) $month = ''; $appointments = get_appointments('', '', $date, $month); foreach($appointments as $appointment) { $description = ''; if($appointment['firstname']) { $description .= ''.$appointment['firstname'].' '.$appointment['lastname'].'
    '; } if($appointment['description']) { $description .= nl2br($appointment['description']); } $events .= '
    '.$description.'
    '.$appointment['starttime'].'
    -
    '.$appointment['endtime'].'
    '; } return $events.'
    '; } function build_previousMonth($month,$year){ $prevMonth = $month - 1; if ($prevMonth == 0) { $prevMonth = 12; } if ($prevMonth == 12){ $prevYear = $year - 1; } else { $prevYear = $year; } return "href=\"../../schedule/?month=".sprintf("%02d", $prevMonth)."&year=$prevYear\""; } function build_nextMonth($month,$year){ $nextMonth = $month + 1; if ($nextMonth == 13) { $nextMonth = 1; } if ($nextMonth == 1){ $nextYear = $year + 1; } else { $nextYear = $year; } return "href=\"../../schedule/?month=".sprintf("%02d", $nextMonth)."&year=$nextYear\""; } ?> $hashkey)); if(mysqli_num_rows($find_query) == 0) { return $hashkey; } else { generatecode($type); } } elseif($type == 'order') { $hashkey = bin2hex(random_bytes(5)); $find_query = select_query('tblclient_requests', "*", array('paycode' => $hashkey)); if(mysqli_num_rows($find_query) == 0) { return rand( ((int) str_pad(1, '11', 0, STR_PAD_RIGHT)), ((int) str_pad(9, '11', 9, STR_PAD_RIGHT)) ); } else { generatecode($type); } } } function markrequest_paid($id, $customer, $type = NULL, $sendNotification = NULL) { if($type == 'paycode') { update_query("tblclient_requests", array("status"=>"Paid", "paid_at"=>date("Y-m-d H:i:s")), array("paycode"=>$id)); } else { update_query("tblclient_requests", array("status"=>"Paid", "paid_at"=>date("Y-m-d H:i:s")), array("id"=>$id)); } if($sendNotification) { if($type == 'paycode') { $select = select_query("tblclient_requests", "*", array("paycode"=>$id)); } else { $select = select_query("tblclient_requests", "*", array("id"=>$id)); } $data = mysqli_fetch_array($select); $customer = select_query("tblclients_customers", "*", array("id"=>$data['customer_relid'])); $customer_data = mysqli_fetch_array($customer); $customer_name = $customer_data['firstname']; if($customer_data['lastname']) $customer_name .= ' '.$customer_data['lastname']; save_send_pushnotification($data['relid'], "primary", "New Payment Notification", $customer_name." has just paid £".$data['amount'].". The request has been marked as Paid.", ""); } } function create_request($v) { $customer_id = $v['customer']; if($customer_id) { } else { $customer_id = create_customer($v); } $arr['relid'] = $_SESSION['uid']; $arr['ordernumber'] = generatecode('order'); $arr['paycode'] = generatecode('paycode'); $arr['customer_relid'] = $customer_id; if($v['action'] == 'newmultirequest') { $arr['amount'] = $v['multiprice']; $arr['multirequest'] = $v['multiarray']; } else { $arr['amount'] = $v['amount']; } $arr['description'] = $v['description']; $arr['status'] = 'Unpaid'; $arr['appointment_id'] = $v['appointment_id']; if($v['email_notification']) $arr['reminders'] = '1'; if($v['sms_notification']) $arr['sms_reminders'] = '1'; $arr['created_at'] = "now()"; if($arr['appointment_id'] == '') $arr['appointment_id'] = '0'; $insert_id = insert_query('tblclient_requests', $arr); die(); logActivity("New Payment Request Created (".$arr['ordernumber'].")", $_SESSION['uid'], $customer_id); if($v['email_notification']) { sendMessage('New Payment Request', $customer_id, array("uid"=>$_SESSION['uid'],"id"=>$insert_id)); } if($v['sms_notification']) { $sms = array("smsname"=>'SMS Payment Request', "userid"=>$_SESSION['uid'],"customerid"=>$customer_id, 'requestid'=>$insert_id, "paycode"=>$arr['paycode']); presend_SMS($sms); } return $insert_id; } function get_request_totals($month, $year) { $query = full_query('SELECT sum(`amount`) as amount, count(*) as count FROM `tblclient_requests` WHERE `relid` = "'.$_SESSION['uid'].'" AND `created_at` >= "'.$year.'-'.$month.'-01 00:00:00" AND `created_at` <= "'.$year.'-'.$month.'-31 23:59:59" '); $data = mysqli_fetch_array($query); return array("amount" => $data['amount'], "count" => $data['count']); } function get_requests($customer, $request_id = NULL, $all = NULL, $status = NULL) { $page = $_GET['page']; if($all) if(!$status) $status = 'Unpaid'; $limit = 10; if($page == '') $page = 1; $sql = "SELECT tblclient_requests.*, tblclients.firstname as seller_firstname, tblclients.lastname as seller_lastname, tblclients.address1 as seller_address1, tblclients.address2 as seller_address2, tblclients.city as seller_city, tblclients.state as seller_state, tblclients.postcode as seller_postcode, tblclients_customers.firstname, tblclients_customers.lastname, tblclients_customers.companyname, tblclients_customers.address1, tblclients_customers.address2, tblclients_customers.city, tblclients_customers.state, tblclients_customers.postcode FROM tblclient_requests LEFT JOIN tblclients_customers ON tblclients_customers.id = tblclient_requests.customer_relid LEFT JOIN tblclients ON tblclients.id = tblclient_requests.relid WHERE tblclient_requests.relid='".$_SESSION['uid']."'"; if($customer) { $sql .= " AND tblclient_requests.customer_relid='".$customer."'"; } if($request_id) { $sql .= " AND tblclient_requests.id='$request_id'"; } if(!empty($all) || !empty($status)) { $sql = "SELECT tblclient_requests.*, tblclients_customers.firstname, tblclients_customers.lastname FROM tblclient_requests LEFT JOIN tblclients_customers ON tblclients_customers.id = tblclient_requests.customer_relid WHERE tblclient_requests.relid='".$_SESSION['uid']."'"; if($status) { $sql .= " AND tblclient_requests.status='$status'"; } if($all > 0) { $limit = $all; } } if($_GET['filter_month'] && $_GET['filter_year']) { $sql .= ' AND `tblclient_requests`.`created_at` >= "'.$_GET['filter_year'].'-'.$_GET['filter_month'].'-01 00:00:00" AND `tblclient_requests`.`created_at` <= "'.$_GET['filter_year'].'-'.$_GET['filter_month'].'-31 23:59:59" '; } if($_GET['filter_name']) { $search = search_customers($_GET['filter_name']); } $sql .= ' ORDER BY `tblclient_requests`.`created_at` DESC'; $query = full_query($sql); while($res= mysqli_fetch_assoc($query)) { if($_GET['filter_name']) { $customerid = $res['customer_relid']; if(!in_array($customerid, $search)) { continue; } } if(!$request_id) { $arr[$res['id']]['id'] = $res['id']; $arr[$res['id']]['customer_relid'] = $res['customer_relid']; $arr[$res['id']]['paycode'] = $res['paycode']; $arr[$res['id']]['firstname'] = $res['firstname']; $arr[$res['id']]['lastname'] = $res['lastname']; $arr[$res['id']]['amount'] = $res['amount']; $arr[$res['id']]['relid'] = $res['relid']; $arr[$res['id']]['tax'] = $res['tax']; $arr[$res['id']]['istaxed'] = $res['istaxed']; $arr[$res['id']]['description'] = $res['description']; $arr[$res['id']]['multirequest'] = json_decode($res['multirequest']); $arr[$res['id']]['status'] = $res['status']; $arr[$res['id']]['linkstatus'] = $res['linkstatus']; $arr[$res['id']]['ordernumber'] = $res['ordernumber']; $arr[$res['id']]['created_at'] = date("d/m/Y G:ia", strtotime($res['created_at'])); $arr[$res['id']]['paid_at'] = date("d/m/Y G:ia", strtotime($res['paid_at'])); $arr[$res['id']]['reminder_sent'] = date("d/m/Y G:ia", strtotime($res['reminder_sent'])); $arr[$res['id']]['reminder_option'] = $res['reminders']; $arr[$res['id']]['sms_reminder_option'] = $res['sms_reminders']; $arr[$res['id']]['invoiceid'] = $res['invoiceid']; $arr[$res['id']]['address1'] = $res['address1']; $arr[$res['id']]['address2'] = $res['address2']; $arr[$res['id']]['city'] = $res['city']; $arr[$res['id']]['state'] = $res['state']; $arr[$res['id']]['postcode'] = $res['postcode']; $arr[$res['id']]['companyname'] = $res['companyname']; $arr[$res['id']]['seller_companyname'] = $res['seller_companyname']; $arr[$res['id']]['seller_firstname'] = $res['seller_firstname']; $arr[$res['id']]['seller_lastname'] = $res['seller_lastname']; $arr[$res['id']]['seller_address1'] = $res['seller_address1']; $arr[$res['id']]['seller_address2'] = $res['seller_address2']; $arr[$res['id']]['seller_city'] = $res['seller_city']; $arr[$res['id']]['seller_state'] = $res['seller_state']; $arr[$res['id']]['seller_postcode'] = $res['seller_postcode']; } else { $arr['id'] = $res['id']; $arr['customer_relid'] = $res['customer_relid']; $arr['relid'] = $res['relid']; $arr['paycode'] = $res['paycode']; $arr['firstname'] = $res['firstname']; $arr['lastname'] = $res['lastname']; $arr['amount'] = $res['amount']; $arr['tax'] = $res['tax']; $arr['istaxed'] = $res['istaxed']; $arr['description'] = $res['description']; $arr['multirequest'] = json_decode($res['multirequest'], true); $arr['status'] = $res['status']; $arr['linkstatus'] = $res['linkstatus']; $arr['ordernumber'] = $res['ordernumber']; $arr['created_at'] = date("d/m/Y G:ia", strtotime($res['created_at'])); $arr['paid_at'] = date("d/m/Y G:ia", strtotime($res['paid_at'])); $arr['reminder_sent'] = date("d/m/Y G:ia", strtotime($res['reminder_sent'])); $arr['reminder_option'] = $res['reminders']; $arr['sms_reminder_option'] = $res['sms_reminders']; $arr['invoiceid'] = $res['invoiceid']; $arr['address1'] = $res['address1']; $arr['address2'] = $res['address2']; $arr['city'] = $res['city']; $arr['state'] = $res['state']; $arr['postcode'] = $res['postcode']; $arr['companyname'] = $res['companyname']; $arr['seller_companyname'] = $res['seller_companyname']; $arr['seller_firstname'] = $res['seller_firstname']; $arr['seller_lastname'] = $res['seller_lastname']; $arr['seller_address1'] = $res['seller_address1']; $arr['seller_address2'] = $res['seller_address2']; $arr['seller_city'] = $res['seller_city']; $arr['seller_state'] = $res['seller_state']; $arr['seller_postcode'] = $res['seller_postcode']; } } $count = 0; if(is_array($arr)) $count = count($arr); $per_page = $limit; $pages = ceil($count / $limit); $start = $page * $per_page - $per_page; $slice = ''; if(is_array($arr)) $slice = array_slice($arr, $start, $per_page); $arr2['limit'] = $limit; $arr2['count'] = $count; $arr2['results'] = $slice; $arr2['pagination'] = pagination($links, ' class="uk-pagination my-3 uk-flex-center" uk-margin="" ', $page, $count, $limit); if($count == 0) { $slice = array(); $arr2['results'] = $slice; } if($all) { return $arr2; } else { return $arr; } } function delete_request($id, $customer) { full_query("DELETE FROM tblclient_requests WHERE id='$id' AND customer_relid='$customer' AND relid='".$_SESSION['uid']."' AND status='Unpaid'"); logActivity("Request Deleted (".$id.")", $_SESSION['uid'], $customer); } "0" AND `relid` = "'.$_SESSION['uid'].'" AND `created_at` >= "'.$year.'-'.$month.'-01 00:00:00" AND `created_at` <= "'.$year.'-'.$month.'-31 23:59:59'); $data = mysqli_fetch_array($query); return $data['count']; } function delete_customer($id) { full_query("DELETE FROM tblclients_customers WHERE id='$id' AND relid='".$_SESSION['uid']."'"); full_query("DELETE FROM tblclients_customers_notes WHERE customer_relid='$id' AND relid='".$_SESSION['uid']."'"); full_query("DELETE FROM tblclients_appointments WHERE customer_relid='$id' AND relid='".$_SESSION['uid']."'"); full_query("DELETE FROM tblclient_requests WHERE customer_relid='$id' AND relid='".$_SESSION['uid']."'"); logActivity("Customer Deleted", $_SESSION['uid']); } function update_customer($id, $customer) { update_query('tblclients_customers', $customer, array("id"=>$id,"relid"=>$_SESSION['uid'])); } function create_customer($v) { $query = select_query("tblclients_customers", "*", array("email"=>$v['email'],"relid"=>$_SESSION['uid'])); if(mysqli_num_rows($query) > 0) { $data = mysqli_fetch_array($query); return $data['id']; } else { $arr['relid'] = $_SESSION['uid']; foreach($v as $k => $val) { $arr[$k] = $val; } $arr['created_at'] = "now()"; $insert_id = insert_query("tblclients_customers", $arr); } logActivity("New Customer Created (".$insert_id.")", $_SESSION['uid']); return $insert_id; } function search_customers($value) { $query = "SELECT id,firstname,lastname,companyname,email FROM tblclients_customers WHERE concat(firstname,' ',lastname) LIKE '%" . $value . "%' LIMIT 0,10"; $result = full_query($query); while ($data = mysqli_fetch_array($result)) { $userids[] = $data["id"]; } return $userids; } function get_customers($customer_id = NULL) { $page = $_GET['page']; $limit = 20; if($page == '') $page = 1; $query = full_query("SELECT tblclients_customers.* FROM tblclients_customers WHERE relid='".$_SESSION['uid']."' ORDER BY created_at ASC"); $sql = "SELECT tblclients_customers.* FROM tblclients_customers WHERE relid='".$_SESSION['uid']."'"; if($customer_id) { $sql .= " AND id='".$customer_id."'"; } $sql .= " ORDER BY created_at DESC"; $query = full_query($sql); while($res= mysqli_fetch_assoc($query)) { $requests = mysqli_num_rows(full_query("SELECT * FROM tblclient_requests WHERE relid='".$_SESSION['uid']."' AND customer_relid='".$res['id']."' AND `status`='Unpaid' ")); $arr[$res['id']]['id'] = $res['id']; $arr[$res['id']]['firstname'] = $res['firstname']; $arr[$res['id']]['lastname'] = $res['lastname']; $arr[$res['id']]['email'] = $res['email']; $arr[$res['id']]['phonenumber'] = $res['phonenumber']; $arr[$res['id']]['requests'] = $requests; $arr[$res['id']]['created_at'] = date("d/m/Y G:ia", strtotime($res['created_at'])); } //$limit = '4'; $count = 0; if(is_array($arr)) $count = count($arr); $per_page = $limit; $pages = ceil($count / $limit); $start = $page * $per_page - $per_page; $slice = ''; if(is_array($arr)) $slice = array_slice($arr, $start, $per_page); $arr2['limit'] = $limit; $arr2['count'] = $count; $arr2['results'] = $slice; $arr2['pagination'] = pagination($links, ' class="uk-pagination my-3 uk-flex-center" uk-margin="" ', $page, $count, $limit); return $arr2; } function reminder_setting($id, $customer, $reminder = NULL) { update_query("tblclient_requests", array("reminders"=>"0"),array("id"=>$id,"customer_relid"=>$customer,"relid"=>$_SESSION['uid'])); if($reminder == 'on') $reminder = 1; update_query("tblclient_requests", array("reminders"=>$reminder),array("id"=>$id,"customer_relid"=>$customer,"relid"=>$_SESSION['uid'])); } ?>'Unlimited'); } else { $payment_limit = array("formatted"=>number_format($payment_limit - $requests['amount'], 2), "text"=>($payment_limit - $requests['amount'])); } $arr['payment_limit'] = $payment_limit; if($payment_requests == 'Unlimited'){ $payment_requests = 'Unlimited'; } else { $payment_requests=$requests['count']; } $arr['payment_requests'] = 'Unlimited'; $arr['sms'] = ($sms_credits['balance'] + $sms_credits['paidbalance']); if($invoice_limit == 'Unlimited'){ $invoice_limit = '9999999999999999'; } else { $invoice_limit = ($invoice_limit - $invoices); } $arr['invoice_requests'] = '9999999999999999'; return $arr; } $note), array("id"=>$id,"relid"=>$_SESSION['uid'],"customer_relid"=>$customer)); } function deletenote($id, $customer) { full_query("delete from tblclients_customers_notes where id='$id' and relid='".$_SESSION['uid']."' and customer_relid='".$customer."'"); } function create_note($v) { $customer_id = $v['customer']; $arr['relid'] = $_SESSION['uid']; $arr['customer_relid'] = $customer_id; $arr['note'] = $v['note']; $arr['created_at'] = "now()"; $insert_id = insert_query('tblclients_customers_notes', $arr); logActivity("New Customer Note Created (".$arr['note'].")", $_SESSION['uid'], $customer_id); return $insert_id; } function get_notes($customer, $request_id = NULL) { $sql = "SELECT * FROM tblclients_customers_notes WHERE relid='".$_SESSION['uid']."' AND customer_relid='".$customer."'"; if($request_id) { $sql .= " AND id='$request_id'"; } $sql .= " ORDER BY `created_at` DESC"; $query = full_query($sql); while($res= mysqli_fetch_assoc($query)) { $arr[$res['id']]['id'] = $res['id']; $arr[$res['id']]['description'] = $res['note']; $arr[$res['id']]['datetime'] = date("d/m/Y G:ia", strtotime($res['created_at'])); } return $arr; }type; } protected function setLoadedModule($module) { $this->loadedmodule = $module; } public function getLoadedModule() { return $this->loadedmodule; } public function getList($type = "") { if ($type) { $this->setType($type); } $base_dir = $this->getBaseModuleDir(); if (is_dir($base_dir)) { $modules = array(); $dh = opendir($base_dir); while (false !== ($module = readdir($dh))) { $module = str_replace(".php", "", $module); if (is_file($this->getModulePath($module))) { $modules[] = $module; } } sort($modules); return $modules; } return false; } protected function getBaseModulesDir() { return ROOTDIR . DIRECTORY_SEPARATOR . "includes" . DIRECTORY_SEPARATOR . "modules"; } public function getBaseModuleDir() { return $this->getBaseModulesDir() . DIRECTORY_SEPARATOR . $this->getType(); } public function getModuleDirectory($module) { return $this->getBaseModuleDir() . DIRECTORY_SEPARATOR . $module; } public function getModulePath($module) { $base_dir = $this->getBaseModuleDir(); switch ($this->getType()) { case "gateways": return $base_dir . DIRECTORY_SEPARATOR . $module . ".php"; default: return $base_dir . DIRECTORY_SEPARATOR . $module . DIRECTORY_SEPARATOR . $module . ".php"; } } /** * Load a given module. * * @todo refactor to use exceptions * * @param string $module * * @return bool */ public function sanitize($type, $var) { if ($type == "int") { $var = (int) $var; } else { if ($type == "a-z") { $var = preg_replace("/[^0-9a-z-]/i", "", $var); } else { if ($type == "a-z_") { $var = preg_replace("/[^0-9a-z-_]/i", "", $var); } else { $var = preg_replace("/[^" . $type . "]/i", "", $var); } } } return $var; } public function load($module) { $module = $this->sanitize("0-9a-z_-", $module); $modpath = $this->getModulePath($module); if (file_exists($modpath)) { include_once $modpath; $this->setLoadedModule($module); $this->setMetaData($this->getMetaData()); return true; } return false; } public function call($function, $params = array()) { if ($this->functionExists($function)) { $params = $this->prepareParams($params); $params = array_merge($this->getParams(), $params); return call_user_func($this->getLoadedModule() . "_" . $function, $params); } return self::FUNCTIONDOESNTEXIST; } public function functionExists($name) { return function_exists($this->getLoadedModule() . "_" . $name); } /** * Retrieves Meta Data from the Loaded Module * * @return mixed */ protected function getMetaData() { $moduleName = $this->getLoadedModule(); if ($this->functionExists("MetaData")) { return $this->call("MetaData"); } } /** * Stores Meta Data to class store * * @param array $metaData * * @return bool */ protected function setMetaData($metaData) { if (is_array($metaData)) { $this->metaData = $metaData; return true; } $this->metaData = array(); return false; } /** * Retrieves a value from the Meta Data * * @param string $keyName The value to fetch * * @return string */ public function getMetaDataValue($keyName) { return array_key_exists($keyName, $this->metaData) ? $this->metaData[$keyName] : ""; } /** * Determines whether a Meta Data value exists * * @param string $keyName The value to check * * @return bool */ public function isMetaDataValueSet($keyName) { return array_key_exists($keyName, $this->metaData); } /** * Retrieves the Display Name for the loaded module * * @return string */ public function getDisplayName() { $DisplayName = $this->getMetaDataValue("DisplayName"); if (!$DisplayName) { $DisplayName = ucfirst($this->getLoadedModule()); } return \Sanitize::makeSafeForOutput($DisplayName); } /** * Retrieves the API Version for the loaded module * * @return string */ public function getAPIVersion() { $APIVersion = $this->getMetaDataValue("APIVersion"); if (!$APIVersion) { $APIVersion = $this->getDefaultAPIVersion(); } return $APIVersion; } /** * Retrieve the Application Link Description from a Module metadata. * * @return string */ public function getApplicationLinkDescription() { return $this->getMetaDataValue("ApplicationLinkDescription"); } /** * Get Default API Version dependant upon module type * * For gateways, which more often than not output data in HTML * forms, we want the default data passed to them to be entity * encoded as it historically has been unless explicity stated * otherwise via the meta data. * * But for other module types, where data is typically used in * direct API communication, decoded should be the default and * it should be up to the modules to make safe for output, * should they even be doing any. * * @return string */ protected function getDefaultAPIVersion() { $moduleType = $this->getType(); switch ($moduleType) { case "gateways": $version = "1.0"; break; default: $version = "1.1"; return $version; } } /** * Pre-process parameters before passing into module * * Performs entity decoding or compat-encoding based on * API Version of the module in use * * This also adds a "whmcsVersion" parameter by default. * * @param array $params * * @return array */ public function prepareParams($params) { if (version_compare($this->getAPIVersion(), "1.1", "<")) { $params = \Sanitize::convertToCompatHtml($params); } else { if (version_compare($this->getAPIVersion(), "1.1", ">=")) { $params = \Sanitize::decode($params); } } return $params; } /** * Add parameter for this module instance * * @param string $key The key to set * @param mixed $value The value to set * * @return $this */ protected function addParam($key, $value) { $this->moduleParams[$key] = $value; return $this; } /** * Get parameters * * Params are formatted according to module API Version * * @return array */ public function getParams() { $moduleParams = $this->moduleParams; return $this->prepareParams($moduleParams); } /** * Get individual parameter value * * @param string $key The key to get * * @return mixed */ public function getParam($key) { $moduleParams = $this->getParams(); return isset($moduleParams[$key]) ? $moduleParams[$key] : ""; } /** * Find a template relative path in one of multiple directories. * * We want modules to be able to have templates in one of four places, with an order * of override, to allow modules to provide a default template for all themes, a * template for specific client themes, and allow client themes to override module * templates. * * We want to check these four paths, in this order, and return the first template we find: * - /templates/activetemplate/modules/moduletype/modulename/templatename.tpl * - /modules/moduletype/modulename/templates/clientThemeName/templatename.tpl * - /modules/moduletype/modulename/templates/templatename.tpl * - /modules/moduletype/modulename/templatename.tpl * * @param string $templateName The filename of the template to find, with or without extension * @return string relative path of the proper template to use. */ public function findTemplate($templateName) { $templateName = preg_replace("/\\.tpl\$/", "", $templateName); $currentTheme = 'Portal'; $templatePath = DIRECTORY_SEPARATOR . "templates" . DIRECTORY_SEPARATOR . $currentTheme; $modulePath = DIRECTORY_SEPARATOR . "modules" . DIRECTORY_SEPARATOR . $this->getType() . DIRECTORY_SEPARATOR . $this->getLoadedModule(); $moduleTemplateProvidedByTheme = $templatePath . DIRECTORY_SEPARATOR . "modules" . DIRECTORY_SEPARATOR . $this->getType() . DIRECTORY_SEPARATOR . $this->getLoadedModule() . DIRECTORY_SEPARATOR . $templateName . ".tpl"; $themeSpecificModuleTemplate = $modulePath . DIRECTORY_SEPARATOR . "templates" . DIRECTORY_SEPARATOR . $currentTheme . DIRECTORY_SEPARATOR . $templateName . ".tpl"; $moduleTemplateInModuleSubdirectory = $modulePath . DIRECTORY_SEPARATOR . "templates" . DIRECTORY_SEPARATOR . $templateName . ".tpl"; $moduleTemplateInModuleDirectory = $modulePath . DIRECTORY_SEPARATOR . $templateName . ".tpl"; if (file_exists(ROOTDIR . $moduleTemplateProvidedByTheme)) { return $moduleTemplateProvidedByTheme; } if (file_exists(ROOTDIR . $themeSpecificModuleTemplate)) { return $themeSpecificModuleTemplate; } if (file_exists(ROOTDIR . $moduleTemplateInModuleSubdirectory)) { return $moduleTemplateInModuleSubdirectory; } if (file_exists(ROOTDIR . $moduleTemplateInModuleDirectory)) { return $moduleTemplateInModuleDirectory; } return ""; } /** * Check if application linking functions are available in the module. * * Both Create and Delete functions are required for support to be determined true. * * @return bool */ public function isApplicationLinkSupported() { return $this->functionExists("CreateApplicationLink") && $this->functionExists("DeleteApplicationLink"); } } '.ucwords($typebox).'! '.urldecode($message).' '; } /* */ ?>$_SESSION['uid'])); } endif; if (!function_exists('getuserdetails')): function getuserdetails($id) { $query = select_query('tblclients', '*', 'id="'.$id.'"'); while($rec[] = mysqli_fetch_assoc($query)):endwhile; return $rec[0]; } endif; if (!function_exists('getverisigndetails')): function getverisigndetails($id) { $query = select_query('tbl_verisign', '*', array("userid" => $id)); while($rec[] = mysqli_fetch_assoc($query)):endwhile; return $rec[0]; } endif; if (!function_exists('getuserdetailbyemail')): function getuserdetailbyemail($email, $detail) { $query = select_query('tblclients', '*', array("email" => $email)); $data = mysqli_fetch_array($query); return $data[$detail]; } endif; ?>getActiveGateways(); } public function getList($type = "") { $modules = parent::getList($type); foreach ($modules as $key => $module) { if ($module == "index") { unset($modules[$key]); } } return $modules; } public static function factory($name) { $gateway = new Gateway(); if (!$gateway->load($name)) { die("Module Not Found"); } if (!$gateway->isLoadedModuleActive()) { die("Module Not Activated"); } return $gateway; } public function getActiveGateways() { if (is_array($this->activeList)) { return $this->activeList; } $this->activeList = array(); $result = select_query("tbl_client_paymentgateways", "DISTINCT gateway", "`setting` NOT IN ('forcesubscriptions', 'forceonetime')"); while ($data = mysqli_fetch_array($result)) { $gateway = $data[0]; if (\Gateways::isNameValid($gateway)) { $this->activeList[] = $gateway; } } return $this->activeList; } public function getMerchantGateways() { return \WHMCS\Database\Capsule::table("tbl_client_paymentgateways")->distinct("gateway")->where("setting", "type")->where("value", self::GATEWAY_CREDIT_CARD)->orderBy("gateway")->pluck("gateway"); } public function isActiveGateway($gateway) { $gateways = $this->getActiveGateways(); return in_array($gateway, $gateways); } public function getDisplayName() { if ($this->getLoadedModule()) { $name = (string) $this->getParam("name"); if ($this->functionExists("get_display_name")) { $currency = getCurrency($_SESSION["uid"], $_SESSION["currency"]); $params = $this->getParams(); $params["name"] = $name; $params["currency"] = $currency; $name = $this->call("get_display_name", $params); } return $name; } $paymentGateways = new \Gateways(); return $paymentGateways->getDisplayName($this->loadedmodule); } public function getAvailableGateways($invoiceid = "") { $validgateways = array(); $result = full_query("SELECT DISTINCT gateway, (SELECT value FROM tbl_client_paymentgateways g2 WHERE g1.gateway=g2.gateway AND setting='name' LIMIT 1) AS `name`, (SELECT `order` FROM tbl_client_paymentgateways g2 WHERE g1.gateway=g2.gateway AND setting='name' LIMIT 1) AS `order` FROM `tbl_client_paymentgateways` g1 WHERE setting='visible' AND value='on' ORDER BY `order` ASC"); while ($data = mysqli_fetch_array($result)) { $validgateways[$data[0]] = $data[1]; } if ($invoiceid) { $invoiceid = (int) $invoiceid; $invoicegateway = get_query_val("tblinvoices", "paymentmethod", array("id" => $invoiceid)); $disabledgateways = array(); $result = select_query("tblinvoiceitems", "", array("type" => "Hosting", "invoiceid" => $invoiceid)); while ($data = mysqli_fetch_assoc($result)) { $relid = $data["relid"]; if ($relid) { $result2 = full_query("SELECT pg.disabledgateways AS disabled FROM tblhosting h LEFT JOIN tblproducts p on h.packageid = p.id LEFT JOIN tblproductgroups pg on p.gid = pg.id where h.id = " . (int) $relid); $data2 = mysqli_fetch_assoc($result2); $gateways = explode(",", $data2["disabled"]); foreach ($gateways as $gateway) { if (array_key_exists($gateway, $validgateways) && $gateway != $invoicegateway) { unset($validgateways[$gateway]); } } } } } return $validgateways; } public function getFirstAvailableGateway() { $gateways = $this->getAvailableGateways(); return key($gateways); } public function load($module, $globalVariable = NULL) { global $GATEWAYMODULE; $GATEWAYMODULE = array(); $module = parent::sanitize("0-9a-z_-", $module); $modulePath = $this->getModulePath($module); $loadStatus = false; if (file_exists($modulePath)) { if (!is_null($globalVariable)) { global ${$globalVariable}; } if (!function_exists($module . "_config") && !function_exists($module . "_link") && !function_exists($module . "_capture")) { require_once $modulePath; } $this->setLoadedModule($module); $this->setMetaData($this->getMetaData()); //$loadStatus = true; } $this->legacyGatewayParams[$module] = $GATEWAYMODULE; if ($loadStatus) { //$this->loadSettings(); } $this->legacyGatewayFields = $GATEWAYMODULE; return $loadStatus; } public function loadSettings() { $gateway = $this->getLoadedModule(); $settings = array("paymentmethod" => $gateway); foreach (GatewaySetting::getForGateway($gateway) as $setting => $value) { $this->addParam($setting, $value); $settings[$setting] = $value; } return $settings; } public function isLoadedModuleActive() { return $this->getParam("type") ? true : false; } public function call($function, $params = []) { $this->addParam("paymentmethod", $this->getLoadedModule()); $userId = 0; if (is_array($params) && array_key_exists("clientdetails", $params)) { $userId = $params["clientdetails"]["userid"]; } if (!$userId) { $userId = $_SESSION["uid"] ?? 0; } $result = parent::call($function, $params); return $result; } private function migrateUpdatedCardData(\WHMCS\User\Client $client, \WHMCS\Payment\PayMethod\Model $payMethod) { if ($payMethod->payment instanceof \WHMCS\Payment\Contracts\CreditCardDetailsInterface) { $legacyCardData = getClientDefaultCardDetails($client->id, "forceLegacy"); $payment = $payMethod->payment; if ($legacyCardData["cardnum"]) { $payment->setCardNumber($legacyCardData["cardnum"]); } if ($legacyCardData["cardlastfour"]) { $payment->setLastFour($legacyCardData["cardlastfour"]); } if ($legacyCardData["cardtype"]) { $payment->setCardType($legacyCardData["cardtype"]); } if ($legacyCardData["startdate"]) { $payment->setStartDate(\WHMCS\Carbon::createFromCcInput($legacyCardData["startdate"])); } if ($legacyCardData["expdate"]) { $payment->setExpiryDate(\WHMCS\Carbon::createFromCcInput($legacyCardData["expdate"])); } if ($legacyCardData["issuenumber"]) { $payment->setIssueNumber($legacyCardData["issuenumber"]); } $payment->save(); $client->markCardDetailsAsMigrated(); } } private function processClientAfterCall(\WHMCS\User\Client $clientBeforeCall, array $callParams) { $clientAfterCall = $clientBeforeCall->fresh(); $invoiceModel = \WHMCS\Billing\Invoice::find($callParams["invoiceid"]); if (!$invoiceModel) { return NULL; } if (!$invoiceModel->payMethod || $invoiceModel->payMethod->trashed()) { return NULL; } if ($clientAfterCall->paymentGatewayToken !== $clientBeforeCall->paymentGatewayToken && $invoiceModel->payMethod->payment instanceof \WHMCS\Payment\Contracts\RemoteTokenDetailsInterface) { if ($clientAfterCall->paymentGatewayToken) { $payment = $invoiceModel->payMethod->payment; $payment->setRemoteToken($clientAfterCall->paymentGatewayToken); $payment->save(); $clientAfterCall->paymentGatewayToken = ""; $clientAfterCall->save(); } else { $invoiceModel->payMethod->delete(); } } if ($clientAfterCall->creditCardType !== $clientBeforeCall->creditCardType) { if (!empty($clientAfterCall->creditCardType)) { $this->migrateUpdatedCardData($clientAfterCall, $invoiceModel->payMethod); } else { if (!$clientAfterCall->paymentGatewayToken) { $invoiceModel->payMethod->delete(); } } } } public function activate(array $parameters = array()) { if ($this->isLoadedModuleActive()) { die("Module already active"); } $lastOrder = (int) get_query_val("tbl_client_paymentgateways", "`order`", array("setting" => "name", "gateway" => $this->getLoadedModule()), "order", "DESC"); if (!$lastOrder) { $lastOrder = (int) get_query_val("tbl_client_paymentgateways", "`order`", "", "order", "DESC"); $lastOrder++; } $configData = $this->getConfiguration(); $displayName = $configData["FriendlyName"]["Value"]; $gatewayType = $this->getMetaDataValue("gatewayType"); if (!in_array($gatewayType, array(self::GATEWAY_BANK, self::GATEWAY_CREDIT_CARD, self::GATEWAY_THIRD_PARTY))) { $gatewayType = self::GATEWAY_THIRD_PARTY; if ($this->functionExists("capture")) { $gatewayType = self::GATEWAY_CREDIT_CARD; } } $this->saveConfigValue("name", $displayName, $lastOrder); $this->saveConfigValue("type", $gatewayType); $this->saveConfigValue("visible", "on"); if ($configData["RemoteStorage"]) { $this->saveConfigValue("remotestorage", "1"); } $hookFile = parent::getModuleDirectory($this->getLoadedModule()) . DIRECTORY_SEPARATOR . "hooks.php"; if (file_exists($hookFile)) { $hooks = array_filter(explode(",", \WHMCS\Config\Setting::getValue("GatewayModuleHooks"))); if (!in_array($this->getLoadedModule(), $hooks)) { $hooks[] = $this->getLoadedModule(); } \WHMCS\Config\Setting::setValue("GatewayModuleHooks", implode(",", $hooks)); } $this->load($this->getLoadedModule()); $this->updateConfiguration($parameters); return true; } public function deactivate(array $parameters = array()) { if (!$this->isLoadedModuleActive()) { throw new \WHMCS\Exception\Module\NotActivated("Module not active"); } if (empty($parameters["newGateway"])) { throw new \WHMCS\Exception\Module\NotServicable("New Module Required"); } if ($this->getLoadedModule() != $parameters["newGateway"]) { if ($this->functionExists("deactivate")) { try { $this->call("deactivate"); } catch (\Exception $e) { logActivity("An Error Occurred on " . $this->getDisplayName() . " Deactivate: " . $e->getMessage()); } } $tables = array("tblaccounts", "tbldomains", "tblhosting", "tblhostingaddons", "tblinvoices", "tblorders"); foreach ($tables as $table) { $field = "paymentmethod"; if ($table == "tblaccounts") { $field = "gateway"; } \WHMCS\Database\Capsule::table($table)->where($field, $this->getLoadedModule())->update(array($field => $parameters["newGateway"])); } $configData = $this->getConfiguration(); $displayName = $configData["FriendlyName"]["Value"]; \WHMCS\Database\Capsule::table("tbl_client_paymentgateways")->where("gateway", $this->getLoadedModule())->delete(); $hooks = array_filter(explode(",", \WHMCS\Config\Setting::getValue("GatewayModuleHooks"))); if (in_array($this->getLoadedModule(), $hooks)) { $hooks = array_flip($hooks); unset($hooks[$this->getLoadedModule()]); $hooks = array_flip($hooks); \WHMCS\Config\Setting::setValue("GatewayModuleHooks", implode(",", $hooks)); } if (!function_exists("logAdminActivity")) { require ROOTDIR . DIRECTORY_SEPARATOR . "includes" . DIRECTORY_SEPARATOR . "adminfunctions.php"; } logAdminActivity("Gateway Module Deactivated: '" . $displayName . "'" . " to '" . $parameters["newGatewayName"] . "'"); return true; } else { throw new \WHMCS\Exception\Module\NotImplemented("Invalid New Module"); } } protected function saveConfigValue($setting, $value, $order = 0) { delete_query("tbl_client_paymentgateways", array("gateway" => $this->getLoadedModule(), "setting" => $setting)); insert_query("tbl_client_paymentgateways", array("gateway" => $this->getLoadedModule(), "setting" => $setting, "value" => $value, "order" => $order)); $this->addParam($setting, $value); } public function getConfiguration() { if (!$this->getLoadedModule()) { die("No module loaded to fetch configuration for"); } if ($this->functionExists("config")) { return $this->call("config"); } if ($this->functionExists("activate")) { $module = $this->getLoadedModule(); $legacyDisplayName = isset($this->legacyGatewayParams[$module][$module . "visiblename"]) ? $this->legacyGatewayParams[$module][$module . "visiblename"] : ucfirst($module); $legacyNotes = isset($this->legacyGatewayParams[$module][$module . "notes"]) ? $this->legacyGatewayParams[$module][$module . "notes"] : ""; $this->call("activate"); $response = array_merge(array("FriendlyName" => array("Type" => "System", "Value" => $legacyDisplayName)), defineGatewayFieldStorage(true)); if (!empty($legacyNotes)) { $response["UsageNotes"] = array("Type" => "System", "Value" => $legacyNotes); } return $response; } throw new \WHMCS\Exception\Module\NotImplemented(); } public function updateConfiguration(array $parameters = array()) { if (!$this->isLoadedModuleActive()) { die("Module not active"); } if (0 < count($parameters)) { $configData = $this->getConfiguration(); $displayName = $configData["FriendlyName"]["Value"]; foreach ($parameters as $key => $value) { if (array_key_exists($key, $configData)) { $this->saveConfigValue($key, $value); } } } } public function getAdminActivationForms($moduleName) { return array((new \WHMCS\View\Form())->setUriPrefixAdminBaseUrl("configgateways.php")->setMethod(\WHMCS\View\Form::METHOD_POST)->setParameters(array("token" => generate_token("plain"), "action" => "activate", "gateway" => $moduleName))->setSubmitLabel(\AdminLang::trans("global.activate"))); } public function getAdminManagementForms($moduleName) { return array((new \WHMCS\View\Form())->setUriPrefixAdminBaseUrl("configgateways.php")->setMethod(\WHMCS\View\Form::METHOD_POST)->setParameters(array("manage" => true, "gateway" => $moduleName))->setSubmitLabel(\AdminLang::trans("global.manage"))); } public function getOnBoardingRedirectHtml() { if (!$this->getMetaDataValue("apiOnboarding")) { return ""; } $redirectUrl = $this->getMetaDataValue("apiOnboardingRedirectUrl"); $callbackPath = $this->getMetaDataValue("apiOnboardingCallbackPath"); $admin = \WHMCS\User\Admin::getAuthenticatedUser(); $params = array("firstname" => $admin->firstName, "lastname" => $admin->lastName, "companyname" => \WHMCS\Config\Setting::getValue("CompanyName"), "email" => $admin->email, "whmcs_callback_url" => \App::getSystemUrl() . $callbackPath, "return_url" => fqdnRoutePath("admin-setup-payments-gateways-onboarding-return")); $buttonValue = "Click here if not redirected automatically"; $output = "Redirecting..." . "" . "

    Please wait while you are redirected...

    " . "
    "; foreach ($params as $key => $value) { $output .= ""; } $output .= "" . "
    " . ""; return $output; } public function getWorkflowType() { if ($this->getMetaDataValue("TokenWorkflow") === true) { return static::WORKFLOW_TOKEN; } if ($this->functionExists("credit_card_input")) { return static::WORKFLOW_ASSISTED; } if ($this->functionExists("remoteinput")) { return static::WORKFLOW_REMOTE; } if ($this->functionExists("nolocalcc")) { return static::WORKFLOW_NOLOCALCARDINPUT; } if ($this->functionExists("storeremote")) { return static::WORKFLOW_TOKEN; } if ($this->functionExists("capture") || $this->getMetaDataValue("gatewayType") === self::GATEWAY_CREDIT_CARD && $this->getMetaDataValue("processingType") === self::PROCESSING_OFFLINE) { return static::WORKFLOW_MERCHANT; } return static::WORKFLOW_THIRDPARTY; } public function isTokenised() { $tokenizedWorkflows = array(static::WORKFLOW_ASSISTED, static::WORKFLOW_REMOTE, static::WORKFLOW_NOLOCALCARDINPUT, static::WORKFLOW_TOKEN); return in_array($this->getWorkflowType(), $tokenizedWorkflows); } public function supportsLocalBankDetails() { return $this->functionExists("localbankdetails"); } public function supportsAutoCapture() { return $this->functionExists("capture") || $this->getProcessingType() == self::PROCESSING_OFFLINE; } public function getBaseGatewayType() { $type = "3rdparty"; if ($this->supportsAutoCapture()) { $type = "creditcard"; } if ($this->supportsLocalBankDetails()) { $type = "bankaccount"; } return $type; } public function getProcessingType() { if ($this->isMetaDataValueSet("processingType")) { return $this->getMetaDataValue("processingType"); } return null; } public function isSupportedCurrency($currencyCode) { if (!$this->isMetaDataValueSet("supportedCurrencies") || in_array($currencyCode, $this->getMetaDataValue("supportedCurrencies"))) { return true; } return false; } } "name"), "order", "ASC"); while ($data = mysql_fetch_array($result)) { $this->displaynames[$data["gateway"]] = $data["value"]; } return $this->displaynames; } public function getDisplayName($gateway) { if (empty($this->displaynames)) { $this->getDisplayNames(); } return array_key_exists($gateway, $this->displaynames) ? $this->displaynames[$gateway] : $gateway; } public static function isNameValid($gateway) { if (!is_string($gateway) || empty($gateway)) { return false; } if (!ctype_alnum(str_replace(array("_", "-"), "", $gateway))) { return false; } return true; } public static function getActiveGateways() { if (is_array(self::$gateways)) { return self::$gateways; } self::$gateways = array(); $result = select_query("tbl_client_paymentgateways", "DISTINCT gateway", ""); while ($data = mysql_fetch_array($result)) { $gateway = $data[0]; if (Gateways::isNameValid($gateway)) { self::$gateways[] = $gateway; } } return self::$gateways; } public function isActiveGateway($gateway) { $gateways = $this->getActiveGateways(); return in_array($gateway, $gateways); } public static function makeSafeName($gateway) { $validgateways = Gateways::getActiveGateways(); return in_array($gateway, $validgateways) ? $gateway : ""; } public function getAvailableGateways($invoiceid = "") { $validgateways = array(); $result = full_query("SELECT DISTINCT gateway, (SELECT value FROM tbl_client_paymentgateways g2 WHERE g1.gateway=g2.gateway AND setting='name' LIMIT 1) AS `name`, (SELECT `order` FROM tbl_client_paymentgateways g2 WHERE g1.gateway=g2.gateway AND setting='name' LIMIT 1) AS `order` FROM `tbl_client_paymentgateways` g1 WHERE setting='visible' AND value='on' ORDER BY `order` ASC"); while ($data = mysql_fetch_array($result)) { $validgateways[$data[0]] = $data[1]; } if ($invoiceid) { $invoiceid = (int) $invoiceid; $invoicegateway = get_query_val("tblinvoices", "paymentmethod", array("id" => $invoiceid)); $result = select_query("tblinvoiceitems", "", array("type" => "Hosting", "invoiceid" => $invoiceid)); while ($data = mysql_fetch_assoc($result)) { $relid = $data["relid"]; if ($relid) { $result2 = full_query("SELECT pg.disabledgateways AS disabled FROM tblhosting h LEFT JOIN tblproducts p on h.packageid = p.id LEFT JOIN tblproductgroups pg on p.gid = pg.id where h.id = " . (int) $relid); $data2 = mysql_fetch_assoc($result2); $gateways = explode(",", $data2["disabled"]); foreach ($gateways as $gateway) { if (array_key_exists($gateway, $validgateways) && $gateway != $invoicegateway) { unset($validgateways[$gateway]); } } } } if (array_key_exists($invoicegateway, $validgateways) === false) { $validgateways[$invoicegateway] = get_query_val("tbl_client_paymentgateways", "value", array("setting" => "name", "gateway" => $invoicegateway)); } } return $validgateways; } public function getFirstAvailableGateway() { $gateways = $this->getAvailableGateways(); return key($gateways); } public function getCCDateMonths() { $months = array(); for ($i = 1; $i <= 12; $i++) { $months[] = str_pad($i, 2, "0", STR_PAD_LEFT); } return $months; } public function getCCStartDateYears() { $startyears = array(); for ($i = date("Y") - 12; $i <= date("Y"); $i++) { $startyears[] = $i; } return $startyears; } public function getCCExpiryDateYears() { $expiryyears = array(); for ($i = date("Y"); $i <= date("Y") + 12; $i++) { $expiryyears[] = $i; } return $expiryyears; } } 0) { while($res = mysqli_fetch_assoc($query)) { if($res['type'] == 'global') { $query2 = full_query('SELECT * FROM `tbl_notification_global` WHERE uid="'.$_SESSION['uid'].'" AND notification_id = "'.$res['id'].'" AND `read` = "1"'); if(mysqli_num_rows($query2) == 0) { $arr[$res['id']]['id'] = $res['id']; $arr[$res['id']]['message'] = $res['message']; $arr[$res['id']]['link'] = $res['link']; $arr[$res['id']]['datetime'] = humanTiming($res['datetime']); $arr[$res['id']]['read'] = $res['read']; $arr[$res['id']]['type'] = $res['type']; } } else { $arr[$res['id']]['id'] = $res['id']; $arr[$res['id']]['message'] = $res['message']; $arr[$res['id']]['link'] = $res['link']; $arr[$res['id']]['datetime'] = humanTiming($res['datetime']); $arr[$res['id']]['read'] = $res['read']; $arr[$res['id']]['type'] = $res['type']; } } } return $arr; } 0) { $explode = explode('?', $_SERVER['REQUEST_URI']); if(count($explode) > 1) { $url = str_replace("&page=".$_GET['page'],"", $_SERVER['REQUEST_URI']); $url = str_replace("?page=".$_GET['page'],"", $url); $uri = $url.'&'; } else { $uri = '?'; } $last = ceil( $total / $limit ); $start = ( ( $page - $links ) > 0 ) ? $page - $links : 1; $end = ( ( $page + $links ) < $last ) ? $page + $links : $last; $html = ''; } return $html; } } ?> $invoiceid ); $adminUsername = ''; // Optional for WHMCS 7.2 and later $results = localAPI($command, $postData, $adminUsername); return $results; } function remove_payment_methods($userid, $methodid) { $command = 'DeletePayMethod'; $postData = array( 'clientid'=>$userid, 'paymethodid' => $methodid, ); $adminUsername = ''; // Optional for WHMCS 7.2 and later $results = localAPI($command, $postData, $adminUsername); return $results; } function get_payment_methods($userid) { $command = 'GetPayMethods'; $postData = array( 'clientid' => $userid, ); $adminUsername = ''; // Optional for WHMCS 7.2 and later $results = localAPI($command, $postData, $adminUsername); return $results; } function add_payment_method($v) { $command = 'AddPayMethod'; $postData = array( 'clientid' => $_SESSION['uid'], 'type' => 'CreditCard', 'card_number' => $v['payment']['ccnumber'], 'card_expiry' => $v['payment']['ccexpirydate'], ); $adminUsername = ''; // Optional for WHMCS 7.2 and later $results = localAPI($command, $postData, $adminUsername); return $results; }
    "); } } if(!function_exists('getSiteCurrency')) { function getSiteCurrency($id) { $query = full_query('SELECT * FROM tblcurrencies WHERE suffix="'.$id.'"'); $data = mysqli_fetch_assoc($query); $arr = array(); $arr['suffix'] = $data['suffix']; $arr['prefix'] = $data['prefix']; $arr['rate'] = $data['rate']; return $arr; } } if(!function_exists('sanitize_output')) { function sanitize_output($buffer) { $search = array( '/\>[^\S ]+/s', // strip whitespaces after tags, except space '/[^\S ]+\/' // Remove HTML comments ); $replace = array( '>', '<', '\\1', '' ); $buffer = preg_replace($search, $replace, $buffer); return $buffer; } } ?> $invoiceid, ); $adminUsername = ''; // Optional for WHMCS 7.2 and later $results = localAPI($command, $postData, $adminUsername); return $results; } function api_AddOrder($pid, $price = NULL) { $command = 'AddOrder'; $postData = array( 'clientid' => $_SESSION['uid'], 'pid' => array($pid), 'billingcycle' => array('monthly'), 'paymentmethod' => 'stripe', ); if($price > 0) { $postData['priceoverride'] = $price; } $adminUsername = ''; // Optional for WHMCS 7.2 and later $results = localAPI($command, $postData, $adminUsername); return $results; } function interpretMaskedPasswordChangeForStorage($newPassword, $originalPassword) { if (!$newPassword) { return ""; } if (hasmaskedpasswordchanged($newPassword, $originalPassword)) { return encrypt(WHMCS\Input\Sanitize::decode($newPassword)); } return false; } function localAPI($command, $values, $other = NULL) { $url = 'https://bill.pay-me.co.uk/includes/api.php'; $values['action'] = $command; $values['identifier'] = 'XKqWjLJzmYkQ2Nf6gzESSd7C5B58nJY1'; $values['secret'] = 'qkBZ2Q0pX0BSnytLLLThb10N8QWj28RF'; $values['responsetype'] = 'json'; // Call the API $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'https://bill.pay-me.co.uk/includes/api.php'); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query( $values ) ); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $response = curl_exec($ch); curl_close($ch); // Decode response $jsonData = json_decode($response, true); return $jsonData; } ?>This is a custom output on the footer'; }); ?> 0) { $k = $_GET; if(function_exists($k['function'])) { call_user_func($k['function'], $k); if($v['jquery']) die(); } } else { $v = $_GET; $allowed = array('loginAgain', 'adminLogin'); if(in_array($v['function'], $allowed)) { if(function_exists($v['function'])) { call_user_func($v['function'], $v); } } } }